gpt4 book ai didi

iphone - 在 Core Graphics 中调整图像大小

转载 作者:行者123 更新时间:2023-12-03 18:58:44 24 4
gpt4 key购买 nike

我正在尝试调整 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);

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

那么我怎样才能真正创建一个实际调整大小的图像,而不仅仅是绘制我想要的正确尺寸?

谢谢

最佳答案

问题是您正在创建与图像大小相同的上下文。您想让上下文成为新的大小。这样就不需要剪辑了。

试试这个:

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

我实际上没有测试它,但它至少应该让您了解需要更改的内容。

关于iphone - 在 Core Graphics 中调整图像大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5811795/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com