欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

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

程序员文章站 2023-12-21 09:04:16
需求:uiimage根据屏幕宽度按照自己本身比例改变高度 上代码,为uiimage创建一个category #import "uiimage+uiimage...

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

需求: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的实例代码,希望对大家有所帮助

上一篇:

下一篇: