Quantcast
Channel: Recent Threads — Xamarin Community Forums
Viewing all articles
Browse latest Browse all 204402

Changing the colour of a UIImage at runtime

$
0
0

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


Viewing all articles
Browse latest Browse all 204402

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>