我在UIBezierPath
中定义了一个形状。我还有一个UIImage
。我现在想用UIBezierPath
裁剪这个图像。我该怎么做?
let shape = UIBezierPath(rect: imageRect)
let image = UIImage(cgimage: c)
最佳答案
我正在输入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);
然后保存
[[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];
}
}];
希望对你有帮助
编辑
快速转换
var newLayer = CAShapeLayer()
newLayer.path = shape.cgPath
view.layer.mask = newLayer
var rectToCrop: CGRect = shape.bounds
UIGraphicsBeginImageContext(view.frame.size)
//, NO, 0);
view.layer.render(inContext: UIGraphicsGetCurrentContext())
var image: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
newLayer.removeFromSuperlayer()
newLayer = nil
var imageRef: CGImageRef? = image?.cgImage.cropping(to: rectToCrop)
var croppedImage = UIImage(cgImage: imageRef!, scale: imgVPhoto.image.scale, orientation: imgVPhoto.image.imageOrientation)
CGImageRelease(imageRef)
关于ios - 使用UIBezierPath裁剪图像-入门,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46082370/