通过调用CGContextDrawImage来调整图像的原因

时间:2012-10-19 11:13:44

标签: ios cgcontext

为什么要通过调用CGContextDrawImage.Thanks来旋转图像。

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

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

遵循this解释。我创建了一个解决方案,允许在一个上下文中使用自定义rects绘制多个图像。

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
}

图片示例:

enter image description here

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