3

The following code splits an image into 2. It seems working fine with non-retina devices, however it gives a different output with retina devices. Could someone please help me fix it? Thanks..

My Code

UIImage *img = [UIImage imageNamed:@"apple.png"];

CGSize sz = [img size];
UIGraphicsBeginImageContextWithOptions(CGSizeMake(sz.width/2, sz.height), NO, 0);
[img drawAtPoint:CGPointMake(-sz.width/2, 0)];
UIImage *right = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
rightView = [[[UIImageView alloc] initWithImage:right] autorelease];
rightView.frame = CGRectMake(self.view.frame.size.width/2, 0, self.view.frame.size.width/2, self.view.frame.size.height);

CGImageRef leftRef = CGImageCreateWithImageInRect([img CGImage],CGRectMake(0,0,sz.width/2,sz.height));
UIGraphicsBeginImageContextWithOptions(CGSizeMake(sz.width/2, sz.height), NO, 0);
CGContextRef con = UIGraphicsGetCurrentContext();
CGContextDrawImage(con, CGRectMake(0,0,sz.width/2.0,sz.height), leftRef);
UIImage *left = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImage *rotatedImage = [left imageRotatedByDegrees:180.0];

leftView = [[[UIImageView alloc] initWithImage:rotatedImage] autorelease];
leftView.frame = CGRectMake(0, 0, self.view.frame.size.width/2, self.view.frame.size.height);
leftView.transform = CGAffineTransformMake(-1,0,0,1,0,0);

CGImageRelease(leftRef);


[self.view addSubview:leftView];
[self.view addSubview:rightView];

non-retina

enter image description here

retina

enter image description here

PS: I don't know if this is important but apple.png has a @2x version..

Eiko
  • 25,601
  • 15
  • 56
  • 71
user1526474
  • 925
  • 13
  • 26

2 Answers2

2

The [-UIImage size] property returns the size in points, not in pixels. You probably need to also call [-UIImage scale] to figure out how the image is scaled.

user1118321
  • 25,567
  • 4
  • 55
  • 86
0

When you create the left view with

leftView = [[[UIImageView alloc] initWithImage:rotatedImage] autorelease];, 

you're not specifying the correct scale. Rather than creating your UIImage this way:

UIImage *left = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImage *rotatedImage = [left imageRotatedByDegrees:180.0];

try creating a CGImageRef and then initializing the UIImage using

[UIImage imageWithCGImage:scale:orientation:]

while specifying the correct scale. There are a number of ways to convert the raw image data from the context to a CGImageRef, or you can use the image you've created and use the CGImage property of UIImage.