调整UIImage的画布大小并用颜色填充空白处? [英] Resize UIImage's canvas and fill the empty place with color?

查看:242
本文介绍了调整UIImage的画布大小并用颜色填充空白处?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简而言之,我想还原裁剪操作。在裁剪中,选择一个矩形,然后将图像剪切到指定的矩形。就我而言,我需要做相反的事情-在图像周围添加空白区域并用颜色填充。注意-图片可能具有透明的背景,所以我不能只在另一张图片上绘制图片。

In simple words I want to "revert" the crop operation. In crop you choose a rect and cut the image to the specified rect. In my case I need to do the opposite thing - to add empty space around the image and fill it with color. Note - image may have transparent background so I can't just draw one image over another image.

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

All the input data (rects and image) I already have. How to solve this task?

推荐答案

基本过程:


  1. 创建纯色UIImage

  2. 获取CGContext

  3. 使用(Obj在新UIImage的中心清除矩形-C) CGContextClearRect(CGContextRef c,CGRect rect); 或(Swift) .clear(_ rect:CGRect)

  4. 将原始图像绘制到新图像的透明矩形中

  1. Create a solid-color UIImage
  2. Get a CGContext
  3. Clear a rect in the center of the new UIImage with (Obj-C) CGContextClearRect(CGContextRef c, CGRect rect); or (Swift) .clear(_ rect: CGRect)
  4. Draw the original image into the "transparent rect" of the new image

例如,使用Swift:

Here is an example, using 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)

    }

这篇关于调整UIImage的画布大小并用颜色填充空白处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆