![](/img/trans.png)
[英]Convert android drawable into xamarin.forms ImageSource
[英]Drawable not appearing on Button Xamarin Forms Android
Xamarin.Forms - Android。 我在 Android 平台上使用按钮渲染器将图像添加到 Android.Widget.Button。 Image 文件存储在 Assets 文件夹中,而不是通常的 Drawable 文件夹中。 我在 XAML 中正常设置按钮的 ImageSource,然后在渲染器中获取图像位置并在资产文件夹中搜索它。 drawable 已正确创建并通过检查匹配的宽度和高度等进行确认,但它只是没有显示在按钮本身上。 图像文件具有 AndroidAsset 的构建操作,但我也尝试过 AndroidResource,但它仍然不起作用。
FileImageSource fis = (FileImageSource)Element.ImageSource;
Stream stream = context.Assets.Open("images/" + fis.File);
Drawable d = Drawable.CreateFromStream(stream, null);
stream.Close();
Control.SetCompoundDrawablesWithIntrinsicBounds(null, d, null, null);
您可以像以下代码一样创建自定义渲染器。
[assembly: ExportRenderer(typeof(Xamarin.Forms.Button), typeof(CustomButton.Droid.CustomButton))]
namespace CustomButton.Droid
{
public class CustomButton:ButtonRenderer
{
Context mcontext;
public CustomButton(Context context) : base(context)
{
mcontext = context;
}
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Button> e)
{
base.OnElementChanged(e);
AssetManager assets = mcontext.Assets;
Stream input = assets.Open("main.png");
var mydraw=Drawable.CreateFromStream(input, null);
Control.Background = mydraw;
}
}
}
以 xamarin 形式使用它。
<StackLayout>
<!-- Place new controls here -->
<Label Text="Welcome to Xamarin.Forms!"
HorizontalOptions="Center"
VerticalOptions="CenterAndExpand" />
<Button Text="Button"/>
</StackLayout>
这是运行截图。
更新
如果我使用Control.SetCompoundDrawablesWithIntrinsicBounds(null, mydraw, null, null);
它可以在文本上方显示图像。
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Button> e)
{
base.OnElementChanged(e);
AssetManager assets = mcontext.Assets;
Stream input = assets.Open("person.jpg");
var mydraw = Drawable.CreateFromStream(input, null);
Control.SetCompoundDrawablesWithIntrinsicBounds(null, mydraw, null, null);
}
public class ButtonView : Button {
public new static readonly BindableProperty ImageSourceProperty = BindableProperty.Create(nameof(ImageSource), typeof(string), typeof(ButtonView), null);
public new string ImageSource {
get { return (string)GetValue(ImageSourceProperty); }
set { SetValue(ImageSourceProperty, value); }
}
}
}
然后在渲染器上:
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e) {
base.OnElementPropertyChanged(sender, e);
if(e.PropertyName == ButtonView.ImageSourceProperty.PropertyName) {
SetImage();
}
}
private void SetImage() {
if (Element is ButtonView btn){
Stream stream = context.Assets.Open("images/" + btn.ImageSource);
Drawable d = Drawable.CreateFromStream(stream, null);
stream.Close();
Control.SetCompoundDrawablesWithIntrinsicBounds(null, d, null, null);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.