裁剪方形UIImage到圆角矩形

时间:2016-06-23 05:25:36

标签: ios objective-c uiimage crop rounded-corners

我已经尝试了至少5种不同的方法,但我没有找到任何方法。所有人都至少1-2岁。从那时起苹果公司是否改变了规则?

我拍了一张截图,将它裁剪成一个正方形,然后我试图将它的角落裁剪到半径为15.

使用OpenGL可能有更严肃和确定的方法吗?

目前尝试使用此解决方案,但角落仍然拒绝裁剪:

-(UIImage*) cropImage:(UIImage*)image withPath:(UIBezierPath*)path { // where the UIBezierPath is defined in the UIKit coordinate system (0,0) is top left

    CGRect r = CGPathGetBoundingBox(path.CGPath); // the rect to draw our image in (minimum rect that the path occupies).

    UIGraphicsBeginImageContextWithOptions(r.size, NO, 0.0); // begin image context, with transparency & the scale of the image.
    CGContextRef ctx = UIGraphicsGetCurrentContext();

    CGContextTranslateCTM(ctx, -r.origin.x, -r.origin.y); // translate context so that when we add the path, it starts at (0,0).

    CGContextAddPath(ctx, path.CGPath); // add path.
    CGContextClip(ctx); // clip any future drawing to the path region.

    [image drawInRect:(CGRect){CGPointZero, image.size}]; // draw image

    UIImage* i = UIGraphicsGetImageFromCurrentImageContext(); // get image from context
    UIGraphicsEndImageContext(); // clean up and finish context

    return i; // return image
}

为了澄清,我试图删除我裁剪的像素

我正在传递......

[self cropImage:myImage withPath:[UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, screenImage.size.width, screenImage.size.height) cornerRadius:15.0]]

即使我尝试大大增加转角半径,仍然没有任何反应。

1 个答案:

答案 0 :(得分:0)

此时你可能已经找到了一些解决方案,但是对于接下来的解决方案,这里的解决方案可能有所帮助。这是一个解决方法,因为它使用UIImageView来完成绘图工作,但它工作得很好。

extension UIImage {

    var circle: UIImage? {
        let length = min(size.width, size.height)
        let imageView = UIImageView(frame: CGRect(origin: .zero, size: CGSize(width: length, height: length)))
        imageView.contentMode = .scaleAspectFill
        imageView.image = self
        imageView.layer.cornerRadius = length/2
        imageView.layer.masksToBounds = true
        UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, false, scale)
        guard let context = UIGraphicsGetCurrentContext() else { return nil }
        imageView.layer.render(in: context)
        let result = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return result
    }
}

如果你想要一个更强大的解决方案,这里的这个可能会有所帮助:https://github.com/giacgbj/UIImageSwiftExtensions/