[英]How to use Images in Xamarin.Forms UWP?
我目前正在 Xamarin.Forms UWP 中创建一个示例系统。 我想知道为什么在 UWP 部分中调用图像的代码在 Android 中工作时似乎无法正常工作。 我还想将图像设置为背景,将图像设置为按钮。
我该如何编码才能使其在两个平台上都能正常运行?
这是我使用的代码:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="XamarinFormsDemo.Views.LoginPage"
BackgroundImage="bg3.jpg"
Title="MainPage">
<Label Text="{Binding MainText}" VerticalOptions="Center" HorizontalOptions="Center" />
<StackLayout VerticalOptions="Center"
Padding="40">
<Image Source="ebmslogo1.png"/>
<StackLayout Padding="0,50,0,0">
<Entry x:Name="txtUserName"
Placeholder="Username"
x:Hint="Username"
BackgroundColor="Black"
TextColor="White"/>
<Entry x:Name="txtPassword"
Placeholder="Password"
IsPassword="true"
BackgroundColor="Black"
TextColor="White"/>
<Button Text="LOG IN"
FontSize="14"
BackgroundColor="Teal"
Clicked="NavigateButton_OnClicked"/>
</StackLayout>
</StackLayout>
</ContentPage>
我的图像位于.Droid > Resources > drawable
对于 UWP 中的 Xamarin Forms,图像必须位于项目根目录(而不是 Assets)中,并将构建操作设置为 Content。
然后图像将在 Xamarin Forms 中像在 Android 和 iOS 中一样工作。
对于 UWP Xamarin 表单:
<Image Source="myimage.png"/>
您还可以从此链接中指定创建“scale-xxx”
显然你需要在 uwp 和 android 中使用图像,所以这里是我的解决方案:
<Image x:Name="kitty"/>
kitty.Source = ImageSource.FromResource("stackoverflow.Resources.Images.kitty.png", typeof(MainPage).Assembly);
优势:
缺点:
如果您只想使用您的 uwp 项目而不是另一个,只需将一个文件夹添加到“资产”并让您像这样使用 xaml 源
<Image x:Name="kitty" Source="Assets/Images/kitty.png"/>
在 UWP 项目中创建一个名为 Resources 的文件夹,将图像放在那里,内容作为构建动作
然后使用这个 MarkupExtension
using System;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace XamarinFormsMoshCourse.MarkupExtensions
{
[ContentProperty(nameof(Source))]
public class PlatformResourceImageExtension : IMarkupExtension
{
public string Source { get; set; }
public object ProvideValue(IServiceProvider serviceProvider)
{
if (String.IsNullOrWhiteSpace(Source)) return null;
string imageSource = String.Empty;
switch (Device.RuntimePlatform)
{
case Device.iOS:
{
imageSource = Source;
break;
}
case Device.Android:
{
imageSource = Source;
break;
}
case Device.UWP:
{
imageSource = String.Concat("Resources/", Source);
break;
}
}
return ImageSource.FromFile(imageSource);
}
}
}
添加标记扩展文件夹作为 xaml 命名空间并像这样使用
<Button ImageSource="{local:PlatformResourceImage clock.png}"/>
<Image Source="{local:PlatformResourceImage clock.png}"/>
现在您可以在所有平台上对相同的图像路径使用相同的语法
您可以创建一个文件夹并使用自定义渲染器来更改路径,如下所示:
[assembly: ExportRenderer(typeof(Image), typeof(CustomImageRenderer))]
public class CustomImageRenderer : ImageRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Image> e)
{
if(e.NewElement != null)
{
var source = e.NewElement.Source;
if(source is FileImageSource fileImageSource)
{
fileImageSource.File = $"Assets/{fileImageSource.File}";
}
}
base.OnElementChanged(e);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.