使用核心图形在UIImage上绘制矩形

Joh*_*Fda 7 core-graphics uiimage ios swift

我正在尝试使用Core Graphics在UIImage的中心放置一个矩形,大致如下所示:

在此输入图像描述

到目前为止这是我的代码:

func drawRectangleOnImage(image: UIImage) -> UIImage {
    let imageSize = image.size
    let scale: CGFloat = 0
    UIGraphicsBeginImageContextWithOptions(imageSize, false, scale)
    let context = UIGraphicsGetCurrentContext()

    let rectangle = CGRect(x: 0, y: (imageSize.height/2) - 30, width: imageSize.width, height: 60)

    CGContextSetFillColorWithColor(context, UIColor.blackColor().CGColor)
    CGContextSetStrokeColorWithColor(context, UIColor.redColor().CGColor)
    CGContextSetLineWidth(context, 5)
    CGContextAddRect(context, rectangle)
    CGContextDrawPath(context, .Fill)

    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return newImage
}
Run Code Online (Sandbox Code Playgroud)

我感觉好像它没有画在我发送的图像之上,它正在创造一个新的图像.整个东西变成红色,矩形变黑.我想要黑色矩形,其余部分仍应与图像相同.

我究竟做错了什么?

Kur*_*vis 21

我感觉好像它没有画在我发送的图像之上,它正在创造一个新的图像.

没有感情.这就是这段代码的作用.

  1. 创建一个新的上下文
  2. 在其中绘制一个矩形
  3. 使图像脱离上下文,并返回它

在步骤1和步骤2之间,您需要将原始图像绘制到上下文中.

此外,无需设置线宽或笔触颜色,因为您只填充矩形,而不是抚摸它.(如果由于某种原因你看到红色,那不是因为这个代码;你有不同的视图或图像有红色背景吗?)

func drawRectangleOnImage(image: UIImage) -> UIImage {
    let imageSize = image.size
    let scale: CGFloat = 0
    UIGraphicsBeginImageContextWithOptions(imageSize, false, scale)
    let context = UIGraphicsGetCurrentContext()

    image.draw(at: CGPoint.zero)

    let rectangle = CGRect(x: 0, y: (imageSize.height/2) - 30, width: imageSize.width, height: 60)

    CGContextSetFillColorWithColor(context, UIColor.black.CGColor)
    CGContextAddRect(context, rectangle)
    CGContextDrawPath(context, .Fill)

    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return newImage
}
Run Code Online (Sandbox Code Playgroud)

您可以通过使用更高级别的UIKit API进行绘制来进一步简化.

func drawRectangleOnImage(image: UIImage) -> UIImage {
    let imageSize = image.size
    let scale: CGFloat = 0
    UIGraphicsBeginImageContextWithOptions(imageSize, false, scale)

    image.draw(at: CGPoint.zero)

    let rectangle = CGRect(x: 0, y: (imageSize.height/2) - 30, width: imageSize.width, height: 60)

    UIColor.black.setFill()
    UIRectFill(rectangle)

    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return newImage
}
Run Code Online (Sandbox Code Playgroud)


小智 7

库尔特·雷维斯的客观C版本答案

-(UIImage *)drawRectangleOnImage:(UIImage *)img rect:(CGRect )rect{
      CGSize imgSize = img.size;
      CGFloat scale = 0;
      UIGraphicsBeginImageContextWithOptions(imgSize, NO, scale);
      [img drawAtPoint:CGPointZero];
      [[UIColor greenColor] setFill];
      UIRectFill(rect);
      UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
      UIGraphicsEndImageContext();
      return newImage;
}
Run Code Online (Sandbox Code Playgroud)