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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5145953/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 20:20:50  来源:igfitidea点击:

How to tint an image/show a colour?

iphoneobjective-cxcode

提问by Andrew

2 things i want to do, which are related:

我想做的两件事是相关的:

  1. Show a block of any colour. So i could change that colour to something else at any time.
  2. Tint a UIImage to be a different colour. An overlay of colour with alpha turned down could work here, but say it was an image which had a transparent background and didn't take up the full square of the image.
  1. 显示任何颜色的块。所以我可以随时将这种颜色更改为其他颜色。
  2. 将 UIImage 着色为不同的颜色。alpha 被关闭的颜色叠加在这里可以工作,但说它是一个具有透明背景的图像并且没有占据图像的整个正方形。

Any ideas?

有任何想法吗?

回答by Daniel Thorpe

Another option, would be to use category methods on UIImage like this...

另一种选择是像这样在 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;
}

回答by Jeff Kelley

The first one is easy. Make a new UIViewand set its background color to whatever color you'd like.

第一个很容易。创建一个新的UIView并将其背景颜色设置为您喜欢的任何颜色。

The second is more difficult. As you mentioned, you can put a new view on top of it with transparency turned down, but to get it to clip in the same places, you'd want to use a mask. Something like this:

第二个更难。正如您所提到的,您可以在关闭透明度的情况下在它上面放置一个新视图,但是要让它在相同的位置剪辑,您需要使用蒙版。像这样的东西:

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];

Keep in mind you'll have to #import <QuartzCore/QuartzCore.h>in the implementation file.

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

回答by lekksi

Here is another way to implement image tinting, especially if you are already using QuartzCore for something else.

这是实现图像着色的另一种方法,特别是如果您已经将 QuartzCore 用于其他用途。

Import QuartzCore:

导入 QuartzCore:

#import <QuartzCore/QuartzCore.h>    

Create transparent CALayer and add it as a sublayer for the image you want to tint:

创建透明 CALayer 并将其添加为要着色的图像的子图层:

CALayer *sublayer = [CALayer layer];
[sublayer setBackgroundColor:[UIColor whiteColor].CGColor];
[sublayer setOpacity:0.3];
[sublayer setFrame:toBeTintedImage.frame];
[toBeTintedImage.layer addSublayer:sublayer];

Add QuartzCore to your projects Framework list (if it isn't already there), otherwise you'll get compiler errors like this:

将 QuartzCore 添加到你的项目框架列表中(如果它还没有),否则你会得到这样的编译器错误:

Undefined symbols for architecture i386: "_OBJC_CLASS_$_CALayer"

回答by PengOne

An easy way to achieve 1 is to create a UILabel or even a UIView and change the backgroundColor as you like.

实现 1 的一种简单方法是创建一个 UILabel 甚至一个 UIView 并根据需要更改 backgroundColor。

There is a way to multiply colours instead of just overlaying them, and that should work for 2. See this tutorial.

有一种方法可以使颜色相乘,而不仅仅是叠加它们,这应该适用于 2。请参阅本教程

回答by user1909319

Try this

尝试这个

   - (void)viewDidLoad
    {
        [super viewDidLoad];
        UIView* maskedView = [self filledViewForPNG:[UIImage imageNamed:@"mask_effect.png"]
                                               mask:[UIImage imageNamed:@"mask_image.png"]
                                          maskColor:[UIColor colorWithRed:.6 green:.2 blue:.7 alpha:1]];


        [self.view addSubview:maskedView];

    }

    -(UIView*)filledViewForPNG:(UIImage*)image mask:(UIImage*)maskImage maskColor:(UIColor*)maskColor
    {
        UIImageView *pngImageView = [[UIImageView alloc] initWithImage:image];
        UIImageView *maskImageView = [[UIImageView alloc] initWithImage:maskImage];

        CGRect bounds;
        if (image) {
            bounds = pngImageView.bounds;
        }
        else
        {
            bounds = maskImageView.bounds;
        }
        UIView* parentView = [[UIView alloc]initWithFrame:bounds];
        [parentView setAutoresizesSubviews:YES];
        [parentView setClipsToBounds:YES];

        UIView *overlay = [[UIView alloc] initWithFrame:bounds];
        [[overlay layer] setMask:[maskImageView layer]];
        [overlay setBackgroundColor:maskColor];

        [parentView addSubview:overlay];
        [parentView addSubview:pngImageView];
        return parentView;
    }