裁剪UIImage - 更改背景颜色

时间:2018-05-19 05:01:29

标签: ios swift

我有一个函数可以将UIImage裁剪为给定矩形的尺寸。有时矩形的一部分落在图像之外。裁剪后,此额外部件的默认颜色为白色。是否可以改变这种颜色?

func crop(mainImage:UIImage, rectangle:CGRect) -> UIImage?{

    let rectSize = CGSize(width: floor(rectangle.width), height: floor(rectangle.height))
    UIGraphicsBeginImageContextWithOptions(rectSize, false, mainImage.scale)
    let context:CGContext = UIGraphicsGetCurrentContext()!;
    mainImage.draw(at: CGPoint(x: -rectangle.origin.x, y: -rectangle.origin.y))
    let croppedImage = UIGraphicsGetImageFromCurrentImageContext()!
    UIGraphicsEndImageContext()
    return croppedImage
}

1 个答案:

答案 0 :(得分:0)

You can use extension 
    extension UIImage {
        func crop( rect: CGRect) -> UIImage {
            var rect = rect
            rect.origin.x*=self.scale
            rect.origin.y*=self.scale
            rect.size.width*=self.scale
            rect.size.height*=self.scale

            let imageRef = self.cgImage!.cropping(to: rect)
            let image = UIImage(cgImage: imageRef!, scale: self.scale, orientation: self.imageOrientation)
            return image
        }
    }

either use method like below

/**
     Extracts image at a given rect from an image
     - parameter rect : rect for which UIImage should be extracted within
     - returns : new UIImage created from rect value supplied
     */
    func imageByCroppingAtRect(_ rect: CGRect) -> UIImage? {

        let imageRef: CGImage? = cgImage?.cropping(to: rect)
        if imageRef == nil {
            return nil
        } else {
            let subImage: UIImage = UIImage(cgImage: imageRef!)
            return subImage
        }
    }