你好,游客 登录 注册 搜索
背景:
阅读新闻

iOS 截取部分图片并显示

[日期:2013-04-18] 来源:Linux社区  作者:Linux [字体:大 中 小]

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

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

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

linux
相关资讯       iOS图片截取  iOS截取 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款