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

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, 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];
}

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

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

       

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