我在每个平台上都有图标资源,并使用 OnPlatform 引用 png 图像。最好像下面的代码一样引用向量 xml。
MapIconImage.Source = Device.OnPlatform(
iOS: ImageSource.FromFile("Icons/location_pin.png"),
Android: ImageSource.FromFile("location_pin.xml"),
WinPhone: ImageSource.FromFile("Icons/location_pin.png"));
其中location_pin.xml是android矢量xml
我知道可以将 png 与相应的 dpi 文件夹一起使用。但在我看来,这个更好。
有什么方法可以在 Xamarin - PCL 中引用 Android 矢量资源吗?
最佳答案
您可以使用简单的按钮自定义渲染器来完成此操作。
页面:
public class VectorImageSourceAndroidPage : ContentPage
{
public VectorImageSourceAndroidPage()
{
Content = new StackLayout
{
Children = {
new VectorImageButton() {
HorizontalOptions=LayoutOptions.CenterAndExpand,
VerticalOptions=LayoutOptions.CenterAndExpand,
WidthRequest=70,
HeightRequest=70,
BackgroundColor=Color.Blue,
Source = Device.OnPlatform(
iOS: "",
Android: "woman",
WinPhone: "")
}
}
};
}
}
public class VectorImageButton : Button
{
public string Source { get; set; }
}
渲染器:
[assembly: ExportRenderer(typeof(VectorImageButton), typeof(VectorImageRenderer))]
namespace ButtonRendererDemo.Droid
{
public class VectorImageRenderer : ButtonRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Button> e)
{
base.OnElementChanged(e);
if (e.NewElement != null)
{
var button = (VectorImageButton)e.NewElement;
var resourceId = (int)typeof(Resource.Drawable).GetField(button.Source).GetValue(null);
Control.Background = Context.GetDrawable(resourceId);
}
}
}
}
可绘制文件夹中的资源:
女人.xml
<?xml version="1.0" encoding="UTF-8" ?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval"
android:id="@+id/shapeBg">
<solid android:color="#ff69b4"/>
<size android:width="70dp" android:height="70dp"/>
</shape>
</item>
<item android:drawable="@drawable/woman_path"/>
</layer-list>
woman_path.xml
<?xml version="1.0" encoding="UTF-8" ?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="70dp"
android:height="70dp"
android:viewportWidth="70"
android:viewportHeight="70">
<path
android:fillColor="#ffffff"
android:pathData="M43 45l-6 0 0 -5c6,-1 11,-6 11,-13 0,-7 -6,-13 -13,-13 -7,0 -13,6 -13,13 0,7
5,12 11,13l0 5 -6 0c-2,0 -2,3 0,3l6 0 0 6c0,2 4,2 4,0l0 -6 6 0c2,0 2,-3
0,-3zm-18 -18c0,-5 5,-10 10,-10 5,0 10,5 10,10 0,5 -5,10 -10,10 -5,0 -10,-5
-10,-10z" />
</vector>
关于android - 在 Xamarin - PCL 中引用 Android 矢量资源?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40931694/