我尝试在UIImage中剪切一个透明的正方形,但我真的不知道从哪里或如何开始。
任何帮助都将不胜感激。
谢谢!
假设您的图像正在一个视图中显示,可能是UIImageView。然后我们可以通过遮罩视图的层在该视图中打一个矩形洞。每个视图都有一个层。我们将为此视图的层应用一个蒙版,它本身是包含图像的图层,我们将在代码中生成此图像。该图像将除了中间某个位置的清晰矩形外都是黑色的。该清晰矩形将导致图像视图中的空洞。
因此,让self.iv
成为这个UIImageView。尝试运行此代码:
CGRect r = self.iv.bounds;
CGRect r2 = CGRectMake(20,20,40,40); // adjust this as desired!
UIGraphicsBeginImageContextWithOptions(r.size, NO, 0);
CGContextRef c = UIGraphicsGetCurrentContext();
CGContextAddRect(c, r2);
CGContextAddRect(c, r);
CGContextEOClip(c);
CGContextSetFillColorWithColor(c, [UIColor blackColor].CGColor);
CGContextFillRect(c, r);
UIImage* maskim = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
CALayer* mask = [CALayer layer];
mask.frame = r;
mask.contents = (id)maskim.CGImage;
self.iv.layer.mask = mask;
例如,在这张图片中,白色正方形并不是叠加在上面的正方形,而是一个洞,展示了它后面窗户背景的白色:CGRect r = self.iv.bounds;
CGRect r2 = CGRectMake(20,20,40,40); // adjust this as desired!
CAShapeLayer* lay = [CAShapeLayer layer];
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddRect(path, nil, r2);
CGPathAddRect(path, nil, r);
lay.path = path;
CGPathRelease(path);
lay.fillRule = kCAFillRuleEvenOdd;
self.iv.layer.mask = lay;
这是一个简单的Swift函数cut#hole#inView
,可以在2017年复制并粘贴使用。
func cut(hole: CGRect, inView view: UIView) {
let path: CGMutablePath = CGMutablePath()
path.addRect(view.bounds)
path.addRect(hole)
let shapeLayer = CAShapeLayer()
shapeLayer.path = path
shapeLayer.fillRule = .evenOdd
view.layer.mask = shapeLayer
}
我只需要@Fattie的版本号,再次感谢!这是更新后的Swift 5.1代码:
private func cut(holeRect: CGRect, inView view: UIView) {
let combinedPath = CGMutablePath()
combinedPath.addRect(view.bounds)
combinedPath.addRect(holeRect)
let maskShape = CAShapeLayer()
maskShape.path = combinedPath
maskShape.fillRule = .evenOdd
view.layer.mask = maskShape
}
如果您希望切口有圆角,您可以将combinedPath.addRect(holeRect)
替换为rectanglePath.addRoundedRect(in: holeRect, cornerWidth: 8, cornerHeight: 8)
。
以下是使用Swift在UIImage上切割一个孔的更新代码(而非UIView):
func cut(hole: CGRect, inView image: UIImage) -> UIImage? {
UIGraphicsBeginImageContext(image.size)
image.draw(at: CGPoint.zero)
let context = UIGraphicsGetCurrentContext()!
let bez = UIBezierPath(rect: hole)
context.addPath(bez.cgPath)
context.clip()
context.clear(CGRect(x:0,y:0,width: image.size.width,height: image.size.height))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
context.clear(someRect)
let frame = CGRect(origin: .zero, size: sz)
let fmt = UIGraphicsImageRendererFormat()
fmt.scale = 1
let image = UIGraphicsImageRenderer(size: sz, format: fmt).image { rc in
.red.setFill()
rc.fill(frame)
rc.cgContext.clear(CGRect(x: 10, y: 10, width: 10, height: 10))
let att = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 10.0)]
"test".draw(in: frame, withAttributes: att)
}
try! image.pngData()!.write(to: "red.png")