调整的UIImage的画布,并用颜色填充空的地方吗?(Resize UIImage's ca

2019-09-28 18:50发布

在简单的话,我想“还原”作物操作。 在作物您选择正确,而且图像中剪切到指定的矩形。 在我来说,我需要做相反的事 - 要添加空白图像周围,并用颜色填充它。 注 - 图像可以有透明的背景,所以我不能只画一个图像在另一个图像。

所有输入数据(rects和图像),我已经有了。 如何解决这个任务?

Answer 1:

基本流程:

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

下面是一个例子,使用夫特:

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!

}

并调用它是这样的:

    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)

    }


文章来源: Resize UIImage's canvas and fill the empty place with color?