UIColor with pattern image and color behind

2019-04-16 02:07发布

问题:

I am trying to set the background color of some UIView element.

I would like to paint it with blue color and a dash pattern on top. I know I could make a new UIView as its child and paint it with

[UIColor colorWithPatternImage:pattern]

but I would specifically want one UIView, so get one UIColor with blue background and pattern image on top.

Marko

EDIT :

Pattern image is like this :

And the result should be :

回答1:

- (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;
}

use above method a s follows

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