2

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

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

1 回答 1

3

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

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

但我的原始答案如下。


CGContextDrawImage函数将缩放图像绘图以适合视图。正如这个函数的文档所说:

将图像绘制到图形上下文中。

Quartz 缩放图像——如果有必要,不成比例地——以适应 rect 参数指定的边界。

唯一看起来很可疑的是那行说:

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

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

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

如果图像仍然没有正确缩放,我建议您仔细检查viewRect. 但CGContextDrawImage绝对绘制在指定范围内缩放的图像CGRect

于 2015-07-02T21:04:56.437 回答