2017-04-14 47 views
3

我想在用戶單擊它時着色PNG。UIImage PNG着色

我在Xcode here中找到了一個例子,但是當我在C#中嘗試時,我無法檢索圖像。

這裏是我寫的代碼:

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

只是想你的代碼。一切都是正確的,但是你並沒有選擇你想要填入PNG的顏色。

變化:

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

到:

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

謝謝,我會嘗試,我看到類似'[tintColor setFill]'在原來的職位,但我想這是一個註釋。 – SunLiker67

+0

不是這樣,原始文章不會告訴你'tintColor'是一個用顏色設置的變量。要使用它,你必須在上下文中調用SetFillColor。所以要使用'tintColor'變量,你可以像初始化它'CGColor tintColor = UIColor.Red.CGColor;',然後調用'context.SetFillColor(tintColor);' – Leze

+0

非常感謝Leze額外的信息。 – SunLiker67