簡體   English   中英

使用UIBezierPath裁剪圖像-入門

[英]Crop an image using UIBezierPath - Beginner

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

如果要在UIImageView中顯示圖像,則可以使用mask屬性。

您需要在路徑之外制作一個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!
     }
}

然后,將其用作掩碼:

myImageView.image = image
myImageView.mask = UIImageView(image: shape.asMaskImage())

暫無
暫無

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

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