iOS中 UIImage根據(jù)屏寬調(diào)整size的實例代碼
更新時間:2017年01月18日 11:24:13 作者:王顏華
最近做項目遇到這樣一個需求,要求UIImage根據(jù)屏幕寬度按照自己本身比例改變高度,下面通過本文給大家分享iOS UIImage根據(jù)屏寬調(diào)整size的實例代碼,需要的朋友參考下吧


需求:UIImage根據(jù)屏幕寬度按照自己本身比例改變高度
上代碼,為UIImage創(chuàng)建一個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的實例代碼,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
iOS UICollectionView實現(xiàn)橫向滑動
這篇文章主要為大家詳細(xì)介紹了iOS UICollectionView實現(xiàn)橫向滑動,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2020-03-03
Flutter開發(fā)Widgets?之?PageView使用示例
這篇文章主要為大家介紹了Flutter開發(fā)Widgets?之?PageView使用示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-10-10

