UIImage PNG coloring

I would like to color the PNG when the user clicks on it.

I found an example in Xcode here , but when I try it in C # I cannot get the image.

Here is the code I wrote:

public UIImage DrawSelectedBorder(UIImage image)
{
    UIGraphics.BeginImageContextWithOptions(image.Size, false, image.CurrentScale); // for correct resolution on retina, thanks @MobileVet
    CGContext context = UIGraphics.GetCurrentContext();

    context.TranslateCTM(0, image.Size.Height);
    context.ScaleCTM((System.nfloat)1.0, (System.nfloat)(-1.0));

    CGRect rect = new CGRect(0, 0, image.Size.Width, image.Size.Height);

    context.SetBlendMode(CGBlendMode.Normal);
    context.SetFillColor(UIColor.Black.CGColor);
    context.FillRect(rect);


    // draw original image
    context.SetBlendMode(CGBlendMode.Normal);
    context.DrawImage(rect,image.CGImage);

    // tint image (losing alpha) - the luminosity of the original image is preserved
    context.SetBlendMode(CGBlendMode.Color);
    context.FillRect(rect);

    // mask by alpha values of original image
    context.SetBlendMode(CGBlendMode.DestinationIn);
    context.DrawImage(rect, image.CGImage);

    UIImage coloredImage = UIGraphics.GetImageFromCurrentImageContext();
    UIGraphics.EndImageContext();

    return coloredImage;
}

      

+3


source to share


1 answer


Just tried my code. That's right, but you haven't chosen the color you want to fill with your PNG.

Edit:

// tint image (losing alpha) - the luminosity of the original image is preserved
context.SetBlendMode(CGBlendMode.Color);
context.FillRect(rect);

      



to:

// tint image (losing alpha) - the luminosity of the original image is preserved
context.SetBlendMode(CGBlendMode.Color);
context.SetFillColor(UIColor.Red.CGColor);
context.FillRect(rect);

      

+3


source







All Articles