0

Why the image is rotated , by calling CGContextDrawImage.Thanks for your help.

// 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);
JCN
  • 11
  • 2

2 Answers2

2

core graphics's coordinated system not like UIKit, you need to calculate the right coordinate. http://blog.ddg.com/?p=10

Gray
  • 7,050
  • 2
  • 29
  • 52
xfx
  • 1,918
  • 1
  • 19
  • 25
0

Following this explanation. I created solution which allow to draw multiple images with custom rects in one context.

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
}

Example with to images:

enter image description here

I know that it can be refactored. I duplicated code for more clarity.

Community
  • 1
  • 1
Kamil Harasimowicz
  • 4,684
  • 5
  • 32
  • 58