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

其实如果是对图片的缩放,而不是剪切部分图片内容,这样写就可以了:

- (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, 50);

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

[image drawInRect:rect];

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

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

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

[cropped release];
}

效果类似这样:

image

这个方法可以帮助我们在后续开发中实现缩略图。但是不符合现在的需求。

于是想了下面的基本思路:

image

这样,需要一个能旋转和向下移动的API。ios提供了C++界面的函数调用:

CGContextRotateCTM,实现角度的转换

CGContextTranslateCTM,可以重新设置坐标系原点,平移坐标系和移动图片是等效的

代码:

- (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);

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

//[image drawInRect:rect];

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

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

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

[cropped release];
}

image

这个结果还有缺陷,可以看到图片是正立的了,但是图片反转了,是个镜像。

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

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