iOS 截取部分图片并显示(3)

解决办法也有,不过不是操作图片了,而是操作图片所在的视图。思路是把视图看作一个位图的矩阵,对它做矩阵变换运算,使视图做镜像反转。写法很简单:

- (void)loadView {
[[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation: UIStatusBarAnimationSlide];
UIImage *image=[UIImage imageNamed:@"1.jpg"];

//[contentView setImage:image];

CGRect rect = CGRectMake(0, 0, 384, 512);//创建矩形框
UIGraphicsBeginImageContext(rect.size);//根据size大小创建一个基于位图的图形上下文
CGContextRef currentContext = UIGraphicsGetCurrentContext();//获取当前quartz 2d绘图环境
CGContextClipToRect(currentContext, rect);//设置当前绘图环境到矩形框


CGContextRotateCTM(currentContext, M_PI);
CGContextTranslateCTM(currentContext, -rect.size.width, -rect.size.height);
//CGContextTranslateCTM(currentContext,0.0,200.0);

CGContextDrawImage(currentContext, rect, image.CGImage);//绘图

//[image drawInRect:rect];

UIImage *cropped = UIGraphicsGetImageFromCurrentImageContext();//获得图片
UIGraphicsEndImageContext();//从当前堆栈中删除quartz 2d绘图环境


UIImageView *contentView = [[UIImageView alloc] initWithFrame:rect];
contentView.image=cropped;

contentView.transform = CGAffineTransformIdentity;
contentView.transform = CGAffineTransformMakeScale(-1.0, 1.0);


self.view=[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
[self.view addSubview:contentView];

[cropped release];
}

这里的转换因子,一个是针对x轴的,一个是针对y轴的。终于可以产生这样的效果了:

image

截取部分图片

截取部分图片,比如:

image

截取左边人像部分。

实现后的代码,效果是这样的:

image

如何实现的呢,这时候才发现,其实根本不需要上面那些转换,如果不使用quartz 2d的话,截取部分图片这么简单:

- (void)loadView {
[[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation: UIStatusBarAnimationSlide];
UIImage *image=[UIImage imageNamed:@"1.jpg"];


CGRect rect = CGRectMake(60, 80, 331, 353);//创建矩形框
UIImageView *contentView = [[UIImageView alloc] initWithFrame:rect];
contentView.image=[UIImage imageWithCGImage:CGImageCreateWithImageInRect([image CGImage], rect)];

self.view=[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
[self.view addSubview:contentView];

[image release];
}

虽然编写代码的过程是曲折的,但是摸到很多有用的东西,都是以后要用到的。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/0ebdb478550697e03b907d4f2311b6b7.html