且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用Quartz在现有图像上绘图来创建新图像?

更新时间:2023-12-05 15:54:04

这些是以下步骤:


  1. 创建一个与图像颜色空间和尺寸相匹配的CGBitmapContext。

  2. 将图像绘制到该上下文中。

  3. 在图像上绘制您想要的任何内容。

  4. 从上下文创建新图像。

  5. Dispose关闭上下文。

  1. Create a CGBitmapContext matching the image's colorspace and dimensions.
  2. Draw the image into that context.
  3. Draw whatever you want on top of the image.
  4. Create a new image from the context.
  5. Dispose off the context.

这是一个获取图像,在其上绘制并返回带有修改内容的新UIImage的方法:

Here's a method that takes an image, draws something on top of it and returns a new UIImage with modified contents:

- (UIImage*)modifiedImageWithImage:(UIImage*)uiImage
{
    // build context to draw in
    CGImageRef image = uiImage.CGImage;
    CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB();
    CGContextRef ctx = CGBitmapContextCreate(NULL,
                                             CGImageGetWidth(image), CGImageGetHeight(image),
                                             8, CGImageGetWidth(image) * 4,
                                             colorspace, kCGImageAlphaPremultipliedLast);
    CGColorSpaceRelease(colorspace);

    // draw original image
    CGRect r = CGRectMake(0, 0, CGImageGetWidth(image), CGImageGetHeight(image));
    CGContextSetBlendMode(ctx, kCGBlendModeCopy);
    CGContextDrawImage(ctx, r, image);
    CGContextSetBlendMode(ctx, kCGBlendModeNormal);

    // draw something
    CGContextAddEllipseInRect(ctx, CGRectInset(r, 10, 10));
    CGContextSetRGBStrokeColor(ctx, 1.0f, 1.0f, 1.0f, 0.5f);
    CGContextSetLineWidth(ctx, 16.0f);
    CGContextDrawPath(ctx, kCGPathStroke);

    CGContextAddEllipseInRect(ctx, CGRectInset(r, 10, 10));
    CGContextSetRGBStrokeColor(ctx, 0.7f, 0.0f, 0.0f, 1.0f);
    CGContextSetLineWidth(ctx, 4.0f);
    CGContextDrawPath(ctx, kCGPathStroke);

    // create resulting image
    image = CGBitmapContextCreateImage(ctx);
    UIImage* newImage = [[[UIImage alloc] initWithCGImage:image] autorelease];
    CGImageRelease(image);
    CGContextRelease(ctx);

    return newImage;
}

要恢复旧图像,只需保留对它的引用。

To restore to old image, just keep a reference to it.

裁剪的事情与上述内容无关,你应该为此创建一个新问题。

The cropping thing is not related to the above and you should create a new question for that.