我正在使用 xamarin.forms 構建一個應用程式。由于影像要在兩種設備上顯示,我選擇使用嵌入影像并遵循
我創建了自定義類:
using System;
using System.Reflection;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace PianoTraining
{
[ContentProperty(nameof(Source))]
public class ImageResourceExtension : IMarkupExtension
{
public string Source { get; set; }
public object ProvideValue(IServiceProvider serviceProvider)
{
if (Source == null)
return null;
return ImageSource.FromResource(Source, typeof(ImageResourceExtension).GetTypeInfo().Assembly);
}
}
}
我通過 XAML 加載我的影像:
<Image x:Name="ChordStatusImage" AbsoluteLayout.LayoutBounds="0.66,0.33" AbsoluteLayout.LayoutFlags="XProportional,YProportional" />
唯一稍有不同的是 xmlns 步驟:我無法設定教程中指定的 xmlns 屬性,因為我已經將其設定為另一個值,以使用自定義呈現器在我的應用程式中顯示 AdMob 廣告(我遵循了本教程)。但是在Android上似乎不是問題。
我以編程方式設定影像的資源:
ChordStatusImage.Source = ImageSource.FromResource("PianoTraining.assets.images.wrongChord.png");
問題是我的影像從未顯示在 iOS 上,無法弄清楚原因。
[編輯] 關于我如何設定源的精確度
The page where the image is loaded is called PianoTrainingPage so I have a class called PianoTrainingPage. The image displayed should change depending on whether the chord is detected or not, and a function is called to load the right image. But because the images weren't displayed, I only set one image programmatically in that function for testing purposes.
I tested several calls to ImageRessource.FromRessource and none of theme solved my problem:
ChordStatusImage.Source = ImageSource.FromResource("PianoTraining.assets.images.wrongChord.png",typeof(ImageResourceExtension).GetTypeInfo().Assembly);(The one from the tutorial) --> The image is displayed on Andrid but not on iosChordStatusImage.Source = ImageSource.FromResource("PianoTraining.assets.images.wrongChord.png",typeof(PianoTrainingPage).GetTypeInfo().Assembly);(because I thought that maybe I was giving the wrong class to typeof) --> The image is displayed on Android but not on iosChordStatusImage.Source = ImageSource.FromResource("PianoTraining.assets.images.wrongChord.png");(using default value for the second parameter) --> The image is displayed on Android but not on ios
In my code, I used the third version because it is the last I tested
uj5u.com熱心網友回復:
正如 Jason 和 ToolmakerSteve 在評論中提到的,有兩種方法可以解決這個問題。
xml
name為您的命名空間添加另一個,允許添加具有不同名稱的相同命名空間。
xmlns:a="clr-namespace:PianoTraining"
xmlns:b="clr-namespace:PianoTraining"
xmlns:c="clr-namespace:PianoTraining"
然后設定對類的參考ImageResourceExtension ,比如
<Image Source="{a:ImageResource PianoTraining.assets.images.wrongChord.png}" />
背后的代碼
只需提供包含在當前程式集中的任何類,例如ImageResourceExtension.
ChordStatusImage.Source = ImageSource.FromResource("PianoTraining.assets.images.wrongChord.png",typeof(ImageResourceExtension ).GetTypeInfo().Assembly);
uj5u.com熱心網友回復:
事實證明,我從一開始就做得很好,typeof有價值,但由于某種原因,我的 mac 麥克風的資料沒有提供給 ios 模擬器。我重新編譯了我的系結庫,現在一切正常。
感謝您的幫助
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/338107.html
