簡體   English   中英

將方形UIImage裁剪為圓角矩形

[英]Crop Square UIImage into Rounded Rect

我嘗試了至少5種在這里找到的不同方法,但是沒有任何效果。 所有年齡都至少為1-2歲。 從那以后,Apple是否更改了規則中的某些內容?

我截取屏幕截圖,將其裁剪為正方形,然后嘗試將其角裁剪為半徑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]]

即使我嘗試大大增加拐角半徑,也仍然沒有任何反應。

在這一點上,您可能已經找到了一些解決方案,但是對於將在此處到達的下一個解決方案,這里的解決方案可能會有所幫助。 這是一種解決方法,因為它使用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/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM