Не отображается на кнопках Xamarin Forms Android - PullRequest
0 голосов
/ 09 марта 2020

Xamarin.Forms - Android. Я использую Button Renderer на платформе Android, чтобы добавить изображение на Android .Widget.Button. Файл изображения хранится в папке Assets, а не в обычной папке Drawable. Я устанавливаю ImageSource кнопки в XAML как обычно, а затем в средстве визуализации я получаю местоположение изображения и ищу его в папке ресурсов. Drawable создается правильно и подтверждается проверкой ширины и высоты, которые соответствуют, et c. но он просто не отображается на самой кнопке. Файл образа имеет действие сборки 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);

Ответы [ 2 ]

0 голосов
/ 17 марта 2020
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);
    }
}
0 голосов
/ 10 марта 2020

Вы можете создать пользовательский рендерер, например, следующий код.

[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>

Вот скриншот.

enter image description here

Обновление

Если бы я использовал 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);
        }

Здесь работает скриншот. enter image description here

...