ios - 缩放 UIImage 以与 CGContextDrawImage 一起使用

标签 ios objective-c uiimage cgcontextdrawimage

我有一个尺寸为 480px x 480px 的图像,我想使用 CGContextDrawImage 将其显示在尺寸为 375px x 375px 的 View 中,如下所示。目前,图像无法缩放以适合 View - 它是以全尺寸绘制的。如何调整下面的代码来缩放图像以适合 View ?

self.image = [UIImage imageNamed:@"image2.png"];
CGContextRef layerContext = CGLayerGetContext(drawingLayer);
CGContextSaveGState(layerContext);
UIGraphicsBeginImageContext (self.viewRect.size);
CGContextTranslateCTM(layerContext, 0, self.image.size.width);
CGContextScaleCTM(layerContext, 1.0, -1.0);
CGContextDrawImage(layerContext, self.viewRect, self.image.CGImage);
UIGraphicsEndImageContext();
CGContextRestoreGState(layerContext);

最佳答案

现在您可能会使用UIGraphicsImageRenderer ,这可以让您摆脱所有这些 CoreGraphics 调用的困扰:

CGRect rect = CGRectMake(0, 0, 375, 375);
UIImage *smallImage = [[[UIGraphicsImageRenderer alloc] initWithBounds:rect] imageWithActions:^(UIGraphicsImageRendererContext * _Nonnull rendererContext) {
    [self.image drawInRect:rect];
}];

但我原来的答案如下。


CGContextDrawImage 函数将缩放图像绘制以适应 View 。正如该函数的文档所述:

Draws an image into a graphics context.

Quartz scales the image—disproportionately, if necessary—to fit the bounds specified by the rect parameter.

唯一看起来非常可疑的是这样一行:

CGContextTranslateCTM(layerContext, 0, self.image.size.width);

首先,您想要垂直平移高度,而不是宽度。其次,您希望按 viewRect 的高度进行平移,而不是按 image 的高度进行平移。因此:

CGContextTranslateCTM(layerContext, 0, self.viewRect.size.height);

如果图像仍然无法正确缩放,我建议您仔细检查 viewRect。但是CGContextDrawImage肯定会绘制在指定的CGRect内缩放的图像。

关于ios - 缩放 UIImage 以与 CGContextDrawImage 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31194044/

相关文章:

IOS + 德尔福 : low memory warnings - possible memory leak with TTexture?

iphone - 是否存在适用于 Windows 7 的 iPhone 模拟器?

ios - iPad 在 iOS 6 上使用 iPhone Storyboard而不是 iPad Storyboard

iphone - 带有 CGBitmapContext 的 Drawrect 太慢了

ios - 如何通过http header 使用基本身份验证从ipad应用程序调用web api服务?

ios - 在 iOS 8 中将照片保存到自定义相册

ios - 在 iTunesConnect 所有权转移后推送通知仍然有效

iphone - 如何使用字母数字值对数组进行排序?

iphone - 添加授权文件

ios - 如何在不进行 NSData 转换的情况下将 url 图像传递给 ios 中的按钮