簡體   English   中英

如何為可拉伸的UIImage着色

[英]How to color a stretchable UIImage

我想為可拉伸的UIImage着色,但是無法使其正常工作。 在本文的幫助下: 如何更改UIImage的顏色我已經成功為UIImage着色,但是當我使其可拉伸時,顏色不會在“新”框架上設置。

這是我使用類別設置顏色的方法:

+ (UIImage *)imageNamed:(NSString *)name withColor:(UIColor *)color
{
    UIImage *image = [UIImage imageNamed:name];
    if (color == nil)
        return image;
    CGRect rect = CGRectMake(0.f, 0.f, image.size.width, image.size.height);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextClipToMask(context, rect, image.CGImage);
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return [UIImage imageWithCGImage:img.CGImage
                               scale:1.0
                         orientation:UIImageOrientationDownMirrored];
}

任何建議表示贊賞...

此代碼應工作:

+ (UIImage *)imageNamed:(NSString *)name withColor:(UIColor *)theColor
{
    UIImage *baseImage = [UIImage imageNamed:name];
    UIGraphicsBeginImageContext(baseImage.size);
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGRect area = CGRectMake(0, 0, baseImage.size.width, baseImage.size.height);
    CGContextScaleCTM(ctx, 1, -1);
    CGContextTranslateCTM(ctx, 0, -area.size.height);
    CGContextSaveGState(ctx);
    CGContextClipToMask(ctx, area, baseImage.CGImage);
    [theColor set];
    CGContextFillRect(ctx, area);
    CGContextRestoreGState(ctx);
    CGContextSetBlendMode(ctx, kCGBlendModeMultiply);
    CGContextDrawImage(ctx, area, baseImage.CGImage);
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

捆綁包中有一個圖像,並使用上述顏色對其進行了着色,這不會修改原始圖像,但會返回一個新圖像。 此新圖像是正常圖像,這意味着您看到的顏色是圖像中的實際位。 如果現在從新創建的圖像(而不是原始圖像)創建新的可拉伸圖像,則它應該是正確的顏色。

如果沒有創建一個小型演示項目,並將其發布到DropBox上,讓我們看一下。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM