【问题标题】:Resize UIImage's canvas and fill the empty place with color?调整 UIImage 的画布大小并用颜色填充空白处?
【发布时间】:2018-05-10 10:24:49
【问题描述】:

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

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

【问题讨论】:

    标签: ios canvas uiimage crop fill


    【解决方案1】:

    基本流程:

    1. 创建纯色 UIImage
    2. 获取 CGContext
    3. 使用 (Obj-C) CGContextClearRect(CGContextRef c, CGRect rect); 或 (Swift) .clear(_ rect: CGRect) 清除新 UIImage 中心的矩形
    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!
    
    }
    

    然后这样称呼它:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-20
      • 2011-04-02
      相关资源
      最近更新 更多