[英]Crop an image using UIBezierPath - Beginner
I have a shape defined in UIBezierPath
. 我在UIBezierPath
定义了一个形状。 I also have an UIImage
. 我也有一个UIImage
。 I now want to crop this image using UIBezierPath
. 我现在想使用UIBezierPath
裁剪此图像。 How can I do this ? 我怎样才能做到这一点 ?
let shape = UIBezierPath(rect: imageRect)
let image = UIImage(cgimage: c)
I am putting Objective C
code. 我把Objective C
代码。 However it is easy to convert in swift3
但是很容易在swift3
转换
Please try below code 请尝试以下代码
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);
And then save 然后保存
[[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];
}
}];
Hope it helps to you 希望对您有帮助
EDIT 编辑
SWIFT Convert SWIFT转换
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)
If you are displaying the image in a UIImageView, you can use the mask property. 如果要在UIImageView中显示图像,则可以使用mask属性。
You need to make a UIImage out of the path: 您需要在路径之外制作一个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!
}
}
Then you use that as the mask: 然后,将其用作掩码:
myImageView.image = image
myImageView.mask = UIImageView(image: shape.asMaskImage())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.