当前位置: 移动技术网 > IT编程>移动开发>IOS > iOS中 UIImage根据屏宽调整size的实例代码

iOS中 UIImage根据屏宽调整size的实例代码

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

煤矿矿长资格证,wm软件,都市风流传

需求:uiimage根据屏幕宽度按照自己本身比例改变高度

上代码,为uiimage创建一个category

#import "uiimage+uiimageextras.h" 
@implementation uiimage (uiimageextras) 
- (uiimage *)imagebyscalingtosize:(cgsize)targetsize 
{ 
 uiimage *sourceimage = self; 
 uiimage *newimage = nil; 
 cgsize imagesize = sourceimage.size; 
 cgfloat width = imagesize.width; 
 cgfloat height = imagesize.height; 
 cgfloat targetwidth = targetsize.width; 
 cgfloat targetheight = targetsize.height; 
 cgfloat scalefactor = 0.0; 
 cgfloat scaledwidth = targetwidth; 
 cgfloat scaledheight = targetheight; 
 cgpoint thumbnailpoint = cgpointmake(0.0,0.0); 
 if (cgsizeequaltosize(imagesize, targetsize) ==no) { 
 cgfloat widthfactor = targetwidth / width; 
 cgfloat heightfactor = targetheight / height; 
 if (widthfactor < heightfactor) 
  scalefactor = widthfactor; 
 else 
  scalefactor = heightfactor; 
 scaledwidth = width * scalefactor; 
 scaledheight = height * scalefactor; 
 // center the image 
 if (widthfactor < heightfactor) { 
  
  thumbnailpoint.y = (targetheight - scaledheight) * 0.5; 
 } else if (widthfactor > heightfactor) { 
  thumbnailpoint.x = (targetwidth - scaledwidth) * 0.5; 
 } 
 } 
 // this is actually the interesting part: 
 uigraphicsbeginimagecontext(targetsize); 
 cgrect thumbnailrect = cgrectzero; 
 thumbnailrect.origin = thumbnailpoint; 
 thumbnailrect.size.width = scaledwidth; 
 thumbnailrect.size.height = scaledheight; 
 [sourceimage drawinrect:thumbnailrect]; 
 newimage =uigraphicsgetimagefromcurrentimagecontext(); 
 uigraphicsendimagecontext(); 
 if(newimage == nil) 
 nslog(@"could not scale image"); 
 return newimage ; 
} 
@end 

在需要使用的地方import然后使用

cgsize size = image.size; 
image = [image imagebyscalingtosize:cgsizemake([uiscreen mainscreen].bounds.size.width,[uiscreen mainscreen].bounds.size.width * (size.height / size.width))]; 
self.imageview.image = image; 

以上所述是小编给大家介绍的ios uiimage根据屏宽调整size的实例代码,希望对大家有所帮助

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网