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

标签 ios swift swift3 uibezierpath croppic

我在 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/

相关文章:

swift - 继承符合协议(protocol)的类

ios - Swift3 中的 "Cannot convert value of type"错误

ios - 当每个部分中的行数不同时,如何获取 numberOfRows 的计数?

ios - 在没有 UILongPressGestureRecognizer 的情况下快速识别长按

c - 在 Swift 中使用 CFNotificationCallback,或者在 Swift 中使用 @convention(c) block

ios - 如何在 Windows 8 上安装 Xcode?

ios - 如何获取childViewController中的parentViewController?

ios - 将 iOS 应用程序提交到应用程序商店应用程序标识符无效

ios - 当我在 xcode 中构建项目时,出现类似 clang 错误 :input files not found 的错误

swift - NSLayout约束: Found nil while unwrapping optional Value