iOS - 在图像上绘画 - 应用蒙版

iOS - Painting on an Image - apply mask

我有一张图片,用户可以在上面作画。对于绘画,我使用类似的东西:

override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
    if (touches.count == 1) {
        let touch = touches.first as! UITouch
        if (touch.tapCount == 1) {
            let touch = touches.first as! UITouch
            let currentPoint = touch.locationInView(self)
            UIGraphicsBeginImageContextWithOptions(self.frame.size, false, self.scale)
            self.image?.drawInRect(CGRectMake(0, 0, self.frame.size.width, self.frame.size.height))
            CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound)
            CGContextSetLineWidth(UIGraphicsGetCurrentContext(), self.width);
            CGContextSetStrokeColorWithColor(UIGraphicsGetCurrentContext(), UIColor.whiteColor().colorWithAlphaComponent(1.0).CGColor);
            CGContextBeginPath(UIGraphicsGetCurrentContext());

            CGContextMoveToPoint(UIGraphicsGetCurrentContext(), startPoint.x, startPoint.y);
            CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), currentPoint.x, currentPoint.y)

            CGContextStrokePath(UIGraphicsGetCurrentContext());
            self.image = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
        }
    }
}

所以结果是原始图像上有一条白线。

然后在下一个屏幕中,我只想显示画好的线,但颜色是透明的,这样可以显示原始图像。我正在尝试应用蒙版,但白线不是完全透明的。

func mergeImages(image: UIImage) {
    let maskImage = UIImage(named: "03-tobacco.png")
    let maskRef = maskImage?.CGImage;

    let mask = CGImageMaskCreate(
        CGImageGetWidth(maskRef),
        CGImageGetHeight(maskRef),
        CGImageGetBitsPerComponent(maskRef),
        CGImageGetBitsPerPixel(maskRef),
        CGImageGetBytesPerRow(maskRef),
        CGImageGetDataProvider(maskRef),
        nil,
        false)
    let masked = CGImageCreateWithMask(image.CGImage, mask)
    let maskedImage = UIImage(CGImage: masked)!
    self.signatureImage.image = maskedImage
}

我怎样才能做到这一点?

您没有使用白线作为遮罩,而是 03-tobacco.png

如果想要白线遮挡,需要更改maskImage和self.image

我是这样解决的,而不是应用蒙版:

UIGraphicsBeginImageContextWithOptions(size, false, 0.0)

let areaSize = CGRect(x: 0, y: 0, width: size.width, height: size.height)
image.drawInRect(areaSize
    maskImage!.drawInRect(areaSize, blendMode: kCGBlendModeSourceIn, alpha: 1.0)        
var newImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()

我先绘制线条,然后使用混合模式 kCGBlendModeSourceIn 应用 "background" 图像,因此它只绘制在那条线上。

希望对大家有所帮助!

为避免不便,请尝试在 UIImageView 之上设置 UIView 的子类。 将其背景颜色设置为清除。 并在 UIView 的子类中隐藏 - 就是这样。