缩放 UIImage 以与 CGContextDrawImage 一起使用

Scaling UIImage for use with with CGContextDrawImage

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

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 函数将缩放图像绘图以适合视图。正如此功能的文档所述:

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.