当前位置: 移动技术网 > 移动技术>移动开发>IOS > iOS中实现imageView任意角度旋转的方法

iOS中实现imageView任意角度旋转的方法

2019年07月24日  | 移动技术网移动技术  | 我要评论

前言

在实际的开发中我们可能会遇到这种情况: 需要对图片进行一定角度的旋转。对于这种需要,我们可能会用uiview的transform进行旋转,但是这样做其实只是对承载imageview的view进行了一定角度的旋转,而imageview并没有旋转。所有这样的做法并不好。

如果需要实现对imageview实现一定角度的旋转,具体步骤是:

      1.将image转成context。

      2.对context进行一定角度的旋转。

      3.将旋转后的context 转化成image。

经过这三个步骤,我们就能够实现将图片真正的做到旋转。

 好了,直接上代码:

#import"uiimage+rotateimagetool.h"
#import<quartzcore/quartzcore.h>
#import<accelerate/accelerate.h>
@implementationuiimage (rotateimagetool)
-(uiimage*)rotateimagewithdegree:(cgfloat)degree{
//将image转化成context
//获取图片像素的宽和高
size_t width =self.size.width*self.scale;
size_t height =self.size.height*self.scale;
//颜色通道为8因为0-255经过了8个颜色通道的变化
//每一行图片的字节数因为我们采用的是argb/rgba所以字节数为width * 4
size_t bytesperrow =width *4;
//图片的透明度通道
cgimagealphainfo info =kcgimagealphapremultipliedfirst;
//配置context的参数:
cgcontextref context =cgbitmapcontextcreate(nil, width, height,8, bytesperrow,cgcolorspacecreatedevicergb(),kcgbitmapbyteorderdefault|info);
if(!context) {
return nil;
}
//将图片渲染到图形上下文中
cgcontextdrawimage(context,cgrectmake(0,0, width, height),self.cgimage);
uint8_t* data = (uint8_t*)cgbitmapcontextgetdata(context);
//旋转欠的数据
vimage_buffer src = { data,height,width,bytesperrow};
//旋转后的数据
vimage_buffer dest= { data,height,width,bytesperrow};
//背景颜色
pixel_8888 backcolor = {0,0,0,0};
//填充颜色
vimage_flags flags = kvimagebackgroundcolorfill;
//旋转context 
vimagerotate_argb8888(&src, &dest,nil, degree *m_pi/180.f, backcolor, flags);
//将conetxt转换成image
cgimageref imageref =cgbitmapcontextcreateimage(context);
uiimage* rotateimage =[uiimageimagewithcgimage:imagerefscale:self.scaleorientation:self.imageorientation];
returnrotateimage;
}

代码中有详细的注释,在这里我就不过多的解释了。感兴趣的可以到github上面下载哦。

下载地址:github.com/15221532825/imagetool  ()

附:ios imageview的image自适应缩放显示全套处理方法

// retina屏幕图片显示问题
[_detailimageview setcontentscalefactor:[[uiscreen mainscreen] scale]];
// 不规则图片显示
_detailimageview.contentmode = uiviewcontentmodescaleaspectfill;
_detailimageview.autoresizingmask = uiviewautoresizingflexibleheight;
// 图片大于或小于显示区域
_detailimageview.clipstobounds = yes;

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对移动技术网的支持。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网