gpt4 book ai didi

ios - 使用 UIBezierPath 裁剪图像 - 初学者

转载 作者:行者123 更新时间:2023-11-28 09:24:40 36 4
gpt4 key购买 nike

我在 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];

}

}];

希望对你有帮助

编辑

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)

关于ios - 使用 UIBezierPath 裁剪图像 - 初学者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46082370/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com