0

问题:我有三个 UIImageViews。一个有一个UIImage,另外两个是-leftImageView & rightImageView。leftImageView 具有图像的左半部分,而右侧具有图像的另一半。我正在尝试使用 Coregraphics 来实现这一点,即在两个图像视图中绘制图像。

但是没有显示正确的图像视图。参考下面的代码:

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

1 回答 1

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));
于 2012-12-04T07:32:22.407 回答