Hi folks, just starting out with some iOS development. I need to put an icon on a button and change the colour of that icon at runtime. I've had a search around and it seems people have managed it with ObjectiveC. So, I thought I'd have a go at trying to implement it in Xamarin. Here is what I've got so far, which if it worked, should change a blue image to a red one
private UIImage GetColoredImage(string imageName)
{
UIImage image = UIImage.FromBundle(imageName);
UIImage coloredImage = null;
UIGraphics.BeginImageContext(image.Size);
using (CGContext context = UIGraphics.GetCurrentContext())
{
context.TranslateCTM(0, image.Size.Height);
context.ScaleCTM(1.0f, -1.0f);
var rect = new RectangleF(0, 0, image.Size.Width, image.Size.Height);
context.ClipToMask(rect, image.CGImage);
context.SetFillColor (UIColor.Red.CGColor);
context.FillRect(rect);
coloredImage = UIGraphics.GetImageFromCurrentImageContext();
UIGraphics.EndImageContext();
}
return coloredImage;
}
Calling code
var i = GetColoredImage("myicon.png");
btn.SetImage (i, UIControlState.Normal);
Can anyone shed any light on this or offer me an alternative that does work?
many thanks