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

时间:2022-09-21 20:43:36

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

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

上代码,为uiimage创建一个category

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#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然后使用

?
1
2
3
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的实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对服务器之家网站的支持!

原文链接:http://blog.csdn.net/u012265444/article/details/54598873