我在UIBezierPath
中定义了一个形状。我也有一个UIImage
。我现在想要使用UIBezierPath
裁剪此图像。我怎么能这样做?
let shape = UIBezierPath(rect: imageRect)
let image = UIImage(cgimage: c)
答案 0 :(得分:0)
我正在使用[1] "https:.../KBOS/2008/01/31/DailyHistory.html"
代码。但是,在Objective C
请尝试以下代码
swift3
然后保存
CAShapeLayer *newLayer = [[CAShapeLayer alloc] init];
newLayer.path = self.shape.CGPath;
[self.view.layer setMask:newLayer];
CGRect rectToCrop = self.shape.bounds;
UIGraphicsBeginImageContext(self.view.frame.size);//, NO, 0);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[newLayer removeFromSuperlayer];
newLayer = nil;
CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], rectToCrop);
UIImage *croppedImage = [UIImage imageWithCGImage:imageRef scale:self.imgVPhoto.image.scale orientation:self.imgVPhoto.image.imageOrientation];
CGImageRelease(imageRef);
希望对你有所帮助
编辑
SWIFT转换
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
//saving cut Image
NSData *imgData = UIImagePNGRepresentation(croppedImage);
if (imgData) {
NSString *imagePath =
if([FileUtility fileExistsAtFilePath:imagePath]) {
[FileUtility deleteFile:imagePath];
}
//need to add this task in BG to avoid blocking of main thread
[imgData writeToFile:imagePath atomically:true];
}
}];
答案 1 :(得分:-1)
如果要在UIImageView中显示图像,则可以使用mask属性。
你需要在路径之外创建一个UIImage:
extension UIBezierPath {
func asMaskImage(fillColor:UIColor = UIColor.black) -> UIImage
{
// Make a graphics context
UIGraphicsBeginImageContextWithOptions(bounds.size, false, 0.0)
let context = UIGraphicsGetCurrentContext()
context!.setFillColor(fillColor.cgColor)
// and fill it!
self.fill()
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
}
然后你用它作为面具:
myImageView.image = image
myImageView.mask = UIImageView(image: shape.asMaskImage())