调整 UIImage 的画布大小并用颜色填充空白处?

Vya*_*cov 5 canvas crop fill uiimage ios

简单来说,我想“恢复”裁剪操作。在裁剪中,您选择一个矩形并将图像剪切到指定的矩形。在我的情况下,我需要做相反的事情 - 在图像周围添加空白空间并用颜色填充它。注意 - 图像可能有透明背景,所以我不能只在另一个图像上绘制一个图像。

我已经拥有的所有输入数据(矩形和图像)。如何解决这个任务?

Don*_*Mag 5

基本流程:

  1. 创建纯色 UIImage
  2. 获取 CGContext
  3. 使用 (Obj-C)CGContextClearRect(CGContextRef c, CGRect rect);或 (Swift)清除新 UIImage 中心的矩形.clear(_ rect: CGRect)
  4. 将原始图像绘制到新图像的“透明矩形”中

这是一个使用 Swift 的示例:

func drawImageOnCanvas(_ useImage: UIImage, canvasSize: CGSize, canvasColor: UIColor ) -> UIImage {

    let rect = CGRect(origin: .zero, size: canvasSize)
    UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)

    // fill the entire image
    canvasColor.setFill()
    UIRectFill(rect)

    // calculate a Rect the size of the image to draw, centered in the canvas rect
    let centeredImageRect = CGRect(x: (canvasSize.width - useImage.size.width) / 2,
                                   y: (canvasSize.height - useImage.size.height) / 2,
                                   width: useImage.size.width,
                                   height: useImage.size.height)

    // get a drawing context
    let context = UIGraphicsGetCurrentContext();

    // "cut" a transparent rectanlge in the middle of the "canvas" image
    context?.clear(centeredImageRect)

    // draw the image into that rect
    useImage.draw(in: centeredImageRect)

    // get the new "image in the center of a canvas image"
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return image!

}
Run Code Online (Sandbox Code Playgroud)

并这样称呼它:

    if let img = UIImage(named: "myimage") {

        let expandedSize = CGSize(width: img.size.width + 60, height: img.size.height + 60)

        let imageOnBlueCanvas = drawImageOnCanvas(img, canvasSize: expandedSize, canvasColor: .blue)

        let v = UIImageView(image: imageOnBlueCanvas)

        view.addSubview(v)

    }
Run Code Online (Sandbox Code Playgroud)