UIColor背后有图案图像和颜色

时间:2013-11-06 08:00:56

标签: ios uiview background-color uicolor

我正在尝试设置某些UIView元素的背景颜色。

我想在上面涂上蓝色和破折号图案。 我知道我可以将新的UIView作为它的孩子并用

绘制它
[UIColor colorWithPatternImage:pattern]

但我特别想要一个UIView,因此请将一个UIColor与蓝色背景和图案图片放在一起。

马尔科

编辑:

模式图像是这样的:enter image description here

结果应该是:enter image description here

1 个答案:

答案 0 :(得分:3)

- (UIImage *)image:(UIImage *)image withColor:(UIColor *)color {
    CGSize backgroundSize = image.size;
    UIGraphicsBeginImageContext(backgroundSize);
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGRect backgroundRect;
    backgroundRect.size = backgroundSize;
    backgroundRect.origin.x = 0;
    backgroundRect.origin.y = 0;
    float r,g,b,a;
    [color getRed:&r green:&g blue:&b alpha:&a];
    CGContextSetRGBFillColor(ctx, r, g, b, a);
    CGContextFillRect(ctx, backgroundRect);

    CGRect imageRect;
    imageRect.size = image.size;
    imageRect.origin.x = (backgroundSize.width - image.size.width)/2;
    imageRect.origin.y = (backgroundSize.height - image.size.height)/2;

    // Unflip the image
    CGContextTranslateCTM(ctx, 0, backgroundSize.height);
    CGContextScaleCTM(ctx, 1.0, -1.0);

    CGContextSetBlendMode(ctx, kCGBlendModeMultiply);
    CGContextDrawImage(ctx, imageRect, image.CGImage);

    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return newImage;
}

使用上面的方法a s

 UIImage *img = [UIImage imageNamed:@"Z2AmQ.png"];
 [self.tmpView setBackgroundColor:[UIColor colorWithPatternImage:[self image:img withColor:[UIColor blueColor]]]];