CGContext的奇怪行为 - iOS

时间:2012-09-30 00:16:36

标签: ios uiimage cgcontext cgcontextdrawimage

以下代码将图像分割为2.对于非视网膜设备似乎工作正常,但是它提供了与视网膜设备不同的输出。有人可以帮我解决一下吗?感谢..

我的代码

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

非视网膜

enter image description here

视网膜

enter image description here

PS:我不知道这是否重要但apple.png有@ 2x版本..

2 个答案:

答案 0 :(得分:2)

[-UIImage size]属性以磅为单位返回大小,而不是以像素为单位。您可能还需要调用[-UIImage scale]来确定图像的缩放方式。

答案 1 :(得分:0)

使用

创建左视图时
leftView = [[[UIImageView alloc] initWithImage:rotatedImage] autorelease];, 

您没有指定正确的比例。而不是这样创建你的UIImage:

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

尝试创建CGImageRef,然后使用

初始化UIImage
[UIImage imageWithCGImage:scale:orientation:]

同时指定正确的比例。有许多方法可以将原始图像数据从上下文转换为CGImageRef,或者您可以使用您创建的图像并使用UIImage的CGImage属性。