iOS中 UIImage根據(jù)屏寬調(diào)整size的實(shí)例代碼


需求:UIImage根據(jù)屏幕寬度按照自己本身比例改變高度
上代碼,為UIImage創(chuàng)建一個(gè)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根據(jù)屏寬調(diào)整size的實(shí)例代碼,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
相關(guān)文章
iOS中創(chuàng)建表格類(lèi)視圖WBDataGridView的實(shí)例代碼
這篇文章主要介紹了iOS中創(chuàng)建表格類(lèi)視圖WBDataGridView的實(shí)例代碼,需要的朋友可以參考下2017-02-02
IOS中自定義類(lèi)中限制使用原生實(shí)例化方法
這篇文章主要介紹了IOS中自定義類(lèi)中限制使用原生實(shí)例化方法的相關(guān)資料,需要的朋友可以參考下2017-09-09
iOS開(kāi)發(fā)中WebView的基本使用方法簡(jiǎn)介
這篇文章主要介紹了iOS開(kāi)發(fā)中WebView的基本使用方法,代碼基于傳統(tǒng)的Objective-C,需要的朋友可以參考下2015-11-11
12個(gè)iOS技術(shù)面試題及答案總結(jié)
這篇文章給大家總結(jié)了在iOS面試的時(shí)候可能會(huì)遇到的12個(gè)技術(shù)面試題,以及這些面試題但答案,這些答案只是給大家一些參考,大家可以再結(jié)合自己理解進(jìn)行回答,有需要的朋友們下面來(lái)一起看看吧。2016-09-09
簡(jiǎn)單講解Objective-C的基本特性及其內(nèi)存管理方式
這篇文章主要介紹了簡(jiǎn)單講解Objective-C的基本特性及其內(nèi)存管理方式,雖然Swift語(yǔ)言出現(xiàn)后iOS和Mac OS應(yīng)用開(kāi)發(fā)方面Objective-C正在成為過(guò)去時(shí),但現(xiàn)有諸多項(xiàng)目仍然在使用,需要的朋友可以參考下2016-01-01

