0

为什么图像被旋转,通过调用 CGContextDrawImage。感谢您的帮助。

// Initialization code
UIImage *img = [UIImage imageNamed:@"logo.png"];
UIImagePNGRepresentation(img);
_image_ref = img.CGImage;

// Drawing code
CGContextRef context = UIGraphicsGetCurrentContext();
CGRect img_rect = CGRectMake(20, 40, 100, 150);
CGContextDrawImage(context, img_rect, _image_ref);
4

2 回答 2

2

核心图形的坐标系不像UIKit,需要计算正确的坐标。 http://blog.ddg.com/?p=10

于 2012-10-19T11:16:51.953 回答
0

按照这个解释。我创建了允许在一个上下文中使用自定义矩形绘制多个图像的解决方案。

func foo() -> UIImage? {
    let image = UIImage(named: "back.png")!

    let contextSize = CGSize(width: 500, height: 500)
    UIGraphicsBeginImageContextWithOptions(contextSize, true, image.scale)
    guard let ctx = UIGraphicsGetCurrentContext() else { return nil }
    guard let cgImage = image.cgImage else { return nil}

    //Start code which can by copy/paste
    let imageRect = CGRect(origin: CGPoint(x: 200.0, y: 200.0), size: image.size) //custom rect
    let ty = imageRect.origin.y + imageRect.size.height //calculate translation Y
    let imageRectWithoutOriginY = CGRect(origin: CGPoint(x: imageRect.origin.x, y: 0), size: imageRect.size)
    ctx.translateBy(x: 0.0, y: ty) //prepare context for custom rect
    ctx.scaleBy(x: 1.0, y: -1.0)

    ctx.draw(cgImage, in: imageRectWithoutOriginY) //draw image

    ctx.translateBy(x: 0.0, y:-ty) //restore default context setup (so you can select new area to place another image)
    ctx.scaleBy(x: 1.0, y: -1.0)
    //End code which can by copy/paste

    let result = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return result
}

图像示例:

在此处输入图像描述

我知道它可以重构。为了更清楚,我复制了代码。

于 2017-04-03T11:54:33.937 回答