博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
缩小 UIImage 的代码
阅读量:7122 次
发布时间:2019-06-28

本文共 1649 字,大约阅读时间需要 5 分钟。

这段“许靖昕”先生的代码将示范如何缩小 UIImage

@implementation UIImage (Extras)  

#pragma mark -  

#pragma mark Scale and crop image  

- (UIImage*)imageByScalingAndCroppingForSize:(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; // scale to fit height  

        else  

                scaleFactor = heightFactor; // scale to fit width  

        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;  

                        }  

        }         

UIGraphicsBeginImageContext(targetSize); // this will crop  

CGRect thumbnailRect = CGRectZero;  

thumbnailRect.origin = thumbnailPoint;  

thumbnailRect.size.width  = scaledWidth;  

thumbnailRect.size.height = scaledHeight;  

[sourceImage drawInRect:thumbnailRect];  

newImage = UIGraphicsGetImageFromCurrentImageContext();  

if(newImage == nil)   

        NSLog(@"could not scale image");  

//pop the context to get back to the default  

UIGraphicsEndImageContext();  

return newImage;  

转载于:https://www.cnblogs.com/greywolf/archive/2012/07/30/2615392.html

你可能感兴趣的文章
观点 | 99%区块链公司会死掉,1%的幸存者都是区块链+
查看>>
监测网络攻击,麻省理工用上了人工智能
查看>>
不看不知道,容器化OpenStack的10个好处
查看>>
移动通信核心网需引入NFV
查看>>
《云计算揭秘企业实施云计算的核心问题》——3.3节云不适合什么场景
查看>>
Spark学习之RDD简单算子
查看>>
ARM第二季度营收增长17%至3.5亿美元
查看>>
Incorporating Copying Mechanism in Sequence-to-Sequence Learning
查看>>
咸阳市位列智慧城市时空云建设年度考核全国第二名
查看>>
Spring 分析摘录
查看>>
IMF总裁:科技变革对于就业的意义何在
查看>>
突破性能瓶颈 东芝发布全新固态硬盘
查看>>
大数据助力农牧业转型升级
查看>>
90亿赔偿没戏了:法官拒甲骨文重审Android侵权案要求
查看>>
智能LED路灯有多种应用功能 将成为智慧城市发展的突破口
查看>>
论大数据对媒体融合的推进作用
查看>>
微软黑科技:DNA存储技术催生方糖大小的数据中心
查看>>
招聘新手段:录段语音来判断求职者是否适合岗位
查看>>
倪光南:大数据安全问题重要性远超数据安全
查看>>
应对网络威胁 有望不再被动“打补丁”
查看>>