【问题标题】:Scaling UIImage for use with with CGContextDrawImage缩放 UIImage 以与 CGContextDrawImage 一起使用
【发布时间】:2015-07-02 20:26:33
【问题描述】:

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

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

【问题讨论】:

    标签: ios objective-c uiimage cgcontextdrawimage


    【解决方案1】:

    现在您可以使用 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范围内缩放的图像。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-27
      • 2013-10-31
      • 1970-01-01
      • 1970-01-01
      • 2014-10-23
      相关资源
      最近更新 更多