在核心图形中调整图像大小

5

我正在尝试调整CGImageRef的大小,以便可以按照我想要的大小在屏幕上绘制它。 因此,我有以下代码:

CGColorSpaceRef colorspace = CGImageGetColorSpace(originalImage);

CGContextRef context = CGBitmapContextCreate(NULL,
                                             CGImageGetWidth(originalImage),
                                             CGImageGetHeight(originalImage),
                                             CGImageGetBitsPerComponent(originalImage),
                                             CGImageGetBytesPerRow(originalImage),
                                             colorspace,
                                             CGImageGetAlphaInfo(originalImage));

if(context == NULL)
    return nil;

CGRect clippedRect = CGRectMake(CGContextGetClipBoundingBox(context).origin.x,
                                CGContextGetClipBoundingBox(context).origin.y,
                                toWidth,
                                toHeight);
CGContextClipToRect(context, clippedRect);

// draw image to context
CGContextDrawImage(context, clippedRect, originalImage);

// extract resulting image from context
CGImageRef imgRef = CGBitmapContextCreateImage(context);

这段代码似乎允许我按照所需大小绘制图像,这很好。

问题在于,即使屏幕上看起来已经被缩放,但实际上我获得的图像并没有被缩放。当我执行:

CGImageGetWidth(imgRef);

它实际上返回的是原始图像的宽度,而不是我在屏幕上看到的宽度。

那么,如何才能创建一个真正被缩放而不仅仅是按照所需大小绘制的图像呢?

谢谢


1
你只是想要绘制调整大小的图像还是实际上需要调整大小?你可以在不进行第二个操作的情况下完成第一个操作(而且可能更快)。 - Robin
1个回答

4
问题在于您使用的上下文与图像大小相同。您需要将上下文设置为新尺寸。然后裁剪就不再必要了。
请尝试以下操作:
CGColorSpaceRef colorspace = CGImageGetColorSpace(originalImage);

CGContextRef context = CGBitmapContextCreate(NULL,
                                             toWidth, // Changed this
                                             toHeight, // Changed this
                                             CGImageGetBitsPerComponent(originalImage),
                                             CGImageGetBytesPerRow(originalImage)/CGImageGetWidth(originalImage)*toWidth, // Changed this
                                             colorspace,
                                             CGImageGetAlphaInfo(originalImage));

if(context == NULL)
    return nil;

// Removed clipping code

// draw image to context
CGContextDrawImage(context, CGContextGetClipBoundingBox(context), originalImage);

// extract resulting image from context
CGImageRef imgRef = CGBitmapContextCreateImage(context);

我实际上没有测试过它,但至少应该让你知道需要改变什么。


既然我们在这个话题上,我想推荐一下我的UIImage类别CKImageAdditions。您可以使用-imageWithSize:contentMode:方法。 - Cory Kilger

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接