Reputation: 599
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!
Upvotes: 2
Views: 2094
Reputation: 4153
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);
}
Upvotes: 2