【问题标题】:Strange behaviour with CGContext - iOSCGContext 的奇怪行为 - iOS
【发布时间】:2012-09-30 00:16:36
【问题描述】:

以下代码将图像拆分为 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];

非视网膜

视网膜

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

【问题讨论】:

    标签: ios uiimage cgcontext cgcontextdrawimage


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      当你用

      创建左视图时
      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 属性。

      【讨论】:

      • 谢谢你的回答。你能给我一个例子吗?
      猜你喜欢
      • 1970-01-01
      • 2017-05-23
      • 2014-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-13
      • 2014-02-16
      相关资源
      最近更新 更多