2

I have a custom ButtonRenderer for Android and I want to change the color of the Image that I use for the button.

This is my ButtonRenderer:

public class VolosBaseButtonRenderer : Xamarin.Forms.Platform.Android.AppCompat.ButtonRenderer {
        public VolosBaseButtonRenderer(Context context) : base(context) { }

        protected override void OnElementChanged(ElementChangedEventArgs<Button> e) {
            base.OnElementChanged(e);

            // What I must do here for change the Image color????

        }

        protected override AppCompatButton CreateNativeControl() {
            var context = new ContextThemeWrapper(Context, Resource.Style.Widget_AppCompat_Button_Borderless);
            var button = new AppCompatButton(context, null, Resource.Style.Widget_AppCompat_Button_Borderless);
            return button;
        }    
    }

I tried these methods but none worked:

Control.Background.SetColorFilter(global::Android.Graphics.Color.Blue, global::Android.Graphics.PorterDuff.Mode.SrcIn);

Control.Background.SetTint(Color.Red.ToAndroid());

If it's possible I can apply a style at the button (but I don't know how to do it).

Any methods will be fine.

Thank you!

1
  • Shouldn't it just be button.SetColourFilter(Color.Blue, PortterDuff.Mode.SrcIn); not sure why you're using 'Control.Background', it's also not the background you're tinting on an image button. Commented Mar 5, 2018 at 10:07

1 Answer 1

2

Assuming your custom Button has two properties, CustomImage, which stores a string of an resource image name, ie "icon.png", and another ImageTintColor, which stores a Xamarin.Forms.Color object, you can use it like so:

var button = (CustomButton)Control.Element;
using (var image = GetScaleDrawable(Resources.GetDrawable(button.CustomImage.Split('.')[0]),
    (int)button.WidthRequest, 
    (int)button.HeightRequest))
{
    if (button.ImageTintColor != Xamarin.Forms.Color.Default)
        image.SetColorFilter(button.ImageTintColor.ToAndroid(), PorterDuff.Mode.SrcAtop);

    this.Control.SetPadding(0, 0, 0, 0);
    this.Control.SetCompoundDrawables(null, image, null, null);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.