I have a public static method that returns a color replaced image (I pass in a black image, and it returns the same image with red instead of black, or whatever color I choose).
It looks like this:
public class ColorImage
{
public static UIImage GetColoredImage(UIImage image, UIColor color)
{
UIImage coloredImage = null;
if (color == null)
{
color = UIColor.FromRGB(44, 132, 248);
}
UIGraphics.BeginImageContextWithOptions(image.Size, false, UIScreen.MainScreen.Scale);
using (CGContext context = UIGraphics.GetCurrentContext())
{
context.TranslateCTM(0, image.Size.Height);
context.ScaleCTM(1.0f, -1.0f);
var rect = new RectangleF(0, 0, (float)image.Size.Width, (float)image.Size.Height);
context.ClipToMask(rect, image.CGImage);
context.SetFillColor(color.CGColor);
context.FillRect(rect);
coloredImage = UIGraphics.GetImageFromCurrentImageContext();
UIGraphics.EndImageContext();
}
return coloredImage;
}
}
I was talking with a colleague and we thought it might be better to store images (color and not color), and colors we plan on using throughout our application in public static fields. That way, if I needed to use one of these colors or images I could just call:
Textfield.BackgroundColor = ColorCache.MainColor;
Textfield.Image = ImageCache.UserImage;
Or something along those lines. This is for an iOS app using Xamarin. Is there a problem with doing it this way? Thought it might even make some of our listviews load faster because they're not grabbing images and processing the color on them over and over.
Instead of loading everything at once like in a static, what would be a better approach is to use caching. So that an image once loaded will be saved in the memory and wont be created next time its asked for. But an image that is not yet asked will not occupy any memory.
You can make use of normal properties or static properties.
Or create a private readonly dictionary with color name and the image as key and value. If the key is available when requested return it else create and add to dictionary and return the image.
Some sample code :