2012-12-04 30 views
0

问题:我有三个UIImageViews。一个是UIImage,另外两个是 - leftImageView & rightImageView。 leftImageView包含图像的左半部分,右图像包含另一半。我正在尝试使用Coregraphics来实现这一点,即在两个图像中绘制图像。在CoreGraphics-iPhone中的两个不同的UIimageviews中分割UIImage

但正确的imageview没有显示出来。参考下面的代码:

UIImage *image = imgView.image; 
CGSize sz = [image size]; 
CGRect leftRect = CGRectMake(0, 0, imgView.frame.size.width/2, imgView.frame.size.height); 
CGRect rightRect = CGRectMake(imgView.frame.size.width/2, 0, imgView.frame.size.width/2, imgView.frame.size.height); 

CGImageRef leftReference = CGImageCreateWithImageInRect([image CGImage], leftRect); 
CGImageRef rightReference = CGImageCreateWithImageInRect([image CGImage], rightRect); 

// Left Image ... 
UIGraphicsBeginImageContextWithOptions(CGSizeMake(leftRect.size.width, leftRect.size.height), NO, 0); 
CGContextRef con = UIGraphicsGetCurrentContext(); 
CGContextDrawImage(con, leftRect,flip(leftReference)); 

imgViewLeft = [[UIImageView alloc] initWithImage:UIGraphicsGetImageFromCurrentImageContext()]; 
UIGraphicsEndImageContext(); 
[self.view addSubview:imgViewLeft]; 


// Right Image ... 
UIGraphicsBeginImageContextWithOptions(CGSizeMake(rightRect.size.width, rightRect.size.height), NO, 0); 
con = UIGraphicsGetCurrentContext(); 
CGContextDrawImage(con, rightRect,flip(rightReference)); 

imgViewRight = [[UIImageView alloc] initWithImage:UIGraphicsGetImageFromCurrentImageContext()]; 
UIGraphicsEndImageContext(); 


[self.view addSubview:imgViewRight]; 

回答

1

我认为你可以使用下面的代码部分。

UIImage *image = [UIImage imageNamed:@"xxx.png"]; // You can change this line. 
BOOL isLeft = YES; // You can change this variable(isLeft = YES : left piece, NO : right piece). 

UIGraphicsBeginImageContext(CGSizeMake(image.size.width/2, image.size.height)); 

CGContextRef context = UIGraphicsGetCurrentContext(); 

if (isLeft) 
    CGContextDrawImage(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, image.size.width, image.size.height), image.CGImage); 
else 
    CGContextDrawImage(UIGraphicsGetCurrentContext(), CGRectMake(- image.size.width/2, 0, image.size.width, image.size.height), image.CGImage); 

UIImage *imageCopy = UIGraphicsGetImageFromCurrentImageContext(); 
UIGraphicsEndImageContext(); 

return imageCopy; 

我现在无法启动此代码,但我认为我的代码几乎是正确的。请试试这个。

编辑:

在您的代码:

// Right Image ... 
UIGraphicsBeginImageContextWithOptions(CGSizeMake(rightRect.size.width, rightRect.size.height), NO, 0); 
con = UIGraphicsGetCurrentContext(); 
CGContextDrawImage(con, rightRect,flip(rightReference)); 

imgViewRight = [[UIImageView alloc] initWithImage:UIGraphicsGetImageFromCurrentImageContext()]; 
UIGraphicsEndImageContext(); 

有一个在三线错误的部分:

CGContextDrawImage(con, rightRect,flip(rightReference)); 

应该

CGContextDrawImage(con, leftRect,flip(rightReference)); 
+0

尊敬@J INX,感谢您的帮助,但我想通了在该方法: '无效CGContextDrawImage(CGContextRef c,CGRect矩形, CGImageRef图像)' 我正在提供rect作为rightRect的坐标开始于下半年的图片。我将在其中提供leftRect。 –

相关问题