我有一个尺寸为 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/