How to draw a shape on top of a UIImage while respecting the image's alpha mask

前端 未结 4 1614
隐瞒了意图╮
隐瞒了意图╮ 2021-01-31 12:29

I need a UIImageView that can draw itself in color or b/w according to a flag:

  BOOL isGrey;

I\'m trying to do it by drawing a black rectangle

4条回答
  •  日久生厌
    2021-01-31 13:21

    To draw a shape while respecting an image's alpha mask, just add one line before you draw:

     CGContextClipToMask(context, self.bounds, image.CGImage);
    
     // example usage
      - (void)drawRect:(CGRect)rect {
    
        if (isGrey) {
                CGContextRef context = UIGraphicsGetCurrentContext();
    
                // flip orientation
                CGContextTranslateCTM(context, 0.0, self.bounds.size.height);
                CGContextScaleCTM(context, 1.0, -1.0);
    
                // draw the image
                CGContextDrawImage(context, self.bounds, self.image.CGImage);
    
                // set the blend mode and draw rectangle on top of image
                CGContextSetBlendMode(context, kCGBlendModeColor);
                CGContextClipToMask(context, self.bounds, image.CGImage); // respect alpha mask
                CGContextSetRGBFillColor(context, 0.0, 0.0, 0.0, 1.0);
                CGContextFillRect(context, rect);               
        } else {
                [self.image drawInRect:rect];
        }
    

    }

提交回复
热议问题