服务器之家

服务器之家 > 正文

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

时间:2021-03-02 16:25     来源/作者:王颜华

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

标签:

相关文章

热门资讯

2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
yue是什么意思 网络流行语yue了是什么梗
yue是什么意思 网络流行语yue了是什么梗 2020-10-11
Intellij idea2020永久破解,亲测可用!!!
Intellij idea2020永久破解,亲测可用!!! 2020-07-29
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总 2020-11-13
返回顶部