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

时间:2017-11-27 08:27:41

标签: ios canvas uiimage crop fill

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

我已经拥有的所有输入数据(rects和图像)。如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

基本流程:

  1. 创建纯色UIImage
  2. 获取CGContext
  3. 使用(Obj-C)CGContextClearRect(CGContextRef c, CGRect rect);或(Swift).clear(_ rect: CGRect)
  4. 清除新UIImage中心的矩形
  5. 将原始图像绘制到新图像的“透明矩形”
  6. 这是一个使用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!
    
    }
    

    并将其称为:

        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)
    
        }