[英]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.