如何着色图像/显示颜色?

And*_*rew 5 iphone xcode objective-c

我想做的2件事,有关:

  1. 显示任何颜色的块.所以我可以随时将其颜色改为其他颜色.
  2. 色调UIImage是一种不同的颜色.阿尔法调低的颜色叠加可以在这里工作,但是说它是一个具有透明背景并且没有占据图像的整个正方形的图像.

有任何想法吗?

Dan*_*rpe 11

另一种选择是在UIImage上使用这样的类别方法......

// Tint the image, default to half transparency if given an opaque colour.
- (UIImage *)imageWithTint:(UIColor *)tintColor {
    CGFloat white, alpha;
    [tintColor getWhite:&white alpha:&alpha];
    return [self imageWithTint:tintColor alpha:(alpha == 1.0 ? 0.5f : alpha)];
}

// Tint the image
- (UIImage *)imageWithTint:(UIColor *)tintColor alpha:(CGFloat)alpha {

    // Begin drawing
    CGRect aRect = CGRectMake(0.f, 0.f, self.size.width, self.size.height);
    UIGraphicsBeginImageContext(aRect.size);

    // Get the graphic context
    CGContextRef c = UIGraphicsGetCurrentContext(); 

    // Converting a UIImage to a CGImage flips the image, 
    // so apply a upside-down translation
    CGContextTranslateCTM(c, 0, self.size.height); 
    CGContextScaleCTM(c, 1.0, -1.0);

    // Draw the image
    [self drawInRect:aRect];

    // Set the fill color space
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextSetFillColorSpace(c, colorSpace);

    // Set the mask to only tint non-transparent pixels
    CGContextClipToMask(c, aRect, self.CGImage);

    // Set the fill color
    CGContextSetFillColorWithColor(c, [tintColor colorWithAlphaComponent:alpha].CGColor);

    UIRectFillUsingBlendMode(aRect, kCGBlendModeColor);

    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();    

    // Release memory
    CGColorSpaceRelease(colorSpace);

    return img;
}
Run Code Online (Sandbox Code Playgroud)

  • 1)要修复"透明像素也有色",在`UIRectFillUsingBlendMode`之前添加`CGContextClipToMask(c,aRect,self.CGImage);`.2)要应用真正的色调,保留图像值,请使用kCGBlendModeColor. (2认同)

Jef*_*ley 10

第一个很容易.制作一个新的UIView并将其背景颜色设置为您想要的任何颜色.

第二个更难.正如你所提到的,你可以在透明度调低的情况下在其上面放置一个新视图,但要让它在相同位置剪辑,你需要使用一个遮罩.像这样的东西:

UIImage *myImage = [UIImage imageNamed:@"foo.png"];

UIImageView *originalImageView = [[UIImageView alloc] initWithImage:myImage];
[originalImageView setFrame:CGRectMake(0.0f, 0.0f, 100.0f, 100.0f)];
[parentView addSubview:originalImageView];

UIView *overlay = [[UIView alloc] initWithFrame:[originalImageView frame]];

UIImageView *maskImageView = [[UIImageView alloc] initWithImage:myImage];
[maskImageView setFrame:[overlay bounds]];

[[overlay layer] setMask:[maskImageView layer]];

[overlay setBackgroundColor:[UIColor redColor]];

[parentView addSubview:overlay];
Run Code Online (Sandbox Code Playgroud)

请记住,您必须#import <QuartzCore/QuartzCore.h>在实现文件中.