2016-04-08 196 views
0

我正在繪製帶有核心圖形的圖像,比我想要將其用作另一圖像的蒙版,但只是獲得清晰的矩形圖像。使用CGImageRef裁剪圖像

看看我的裁剪功能有什麼問題?

UIGraphicsBeginImageContext(CGSizeMake(self.bounds.size.width/0.5, self.bounds.size.height/0.5)) 
    let imageCtx = UIGraphicsGetCurrentContext() 
    CGContextAddArc(imageCtx, CGFloat(self.frame.size.width) , CGFloat(self.frame.size.height), 158, 0, CGFloat(DegreesToRadians(Double(angle))) , 0) 
    CGContextSetLineWidth(imageCtx, 80) 
    CGContextDrawPath(imageCtx, .Stroke) 
    let myMask :CGImageRef = CGBitmapContextCreateImage(UIGraphicsGetCurrentContext())! 

    UIGraphicsEndImageContext() 
    let maskImage = UIImage(CGImage: myMask) 

    let testVideoPreview = UIImage(named: "alex") 
    guard let makedImage = testVideoPreview else {return} 

    var imageMaskOne: CGImageRef = CGImageMaskCreate(CGImageGetWidth(myMask), CGImageGetHeight(myMask), CGImageGetBitsPerComponent(myMask), CGImageGetBitsPerPixel(myMask), CGImageGetBytesPerRow(myMask), CGImageGetDataProvider(myMask), nil,  // Decode is null 
     true)! 

    let masked: CGImageRef = CGImageCreateWithMask(makedImage.CGImage, imageMaskOne)! 

    //Finished 
    let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 350, height: 350)) 
    imageView.image = UIImage(CGImage: masked) 
    self.addSubview(imageView) 

回答

4

如果你只需要創建在一個特定的作物座標有一個更簡單的方法CGImageCreateWithImageInRect

func CGImageCreateWithImageInRect(_ image: CGImage?, _ rect: CGRect) -> CGImage? 

這裏documentation

+0

裁剪矩形部分的完美解決方案。 –