iOS-UIImage+Extension
2019-08-09 本文已影响0人
香蕉你个菠萝
.h
#import <UIKit/UIKit.h>
@interface UIImage (Extension)
//根据图片获取图片的主色调
+ (UIColor *)mostColor:(UIImage*)image;
+ (UIImage *)scaleToSize:(UIImage *)img size:(CGSize)size;
+ (UIImage *)imageByScalingAndCroppingForSize:(CGSize)targetSize;
//压缩图片到指定大小kb
+(UIImage *)scaleImage:(UIImage *)image toKb:(NSInteger)kb;
/**
* 剪切图片为正方形
*
* @param image 原始图片比如size大小为(400x200)pixels
* @param newSize 正方形的size比如400pixels
*
* @return 返回正方形图片(400x400)pixels
*/
- (UIImage *)squareImageFromImage:(UIImage *)image scaledToSize:(CGFloat)newSize;
//图片截取
- (UIImage*)getSubImage:(UIImage *)image mCGRect:(CGRect)mCGRect
centerBool:(BOOL)centerBool;
- (UIImage*)dx_getSubImage:(UIImage *)image mCGRect:(CGRect)mCGRect;
// 加载最原始的图片,没有渲染
+ (instancetype)imageWithOriginalName:(NSString *)imageName;
+ (instancetype)imageWithStretchableName:(NSString *)imageName orginX:(CGFloat)x orginY:(CGFloat)y;
+(UIImage*)createImageWithColor:(UIColor*) color;
@end
.m
#import "UIImage+Extension.h"
@implementation UIImage (Extension)
//根据图片获取图片的主色调
+(UIColor*)mostColor:(UIImage*)image {
#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_6_1
int bitmapInfo = kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedLast;
#else
int bitmapInfo = kCGImageAlphaPremultipliedLast;
#endif
//第一步 先把图片缩小 加快计算速度. 但越小结果误差可能越大
CGSize thumbSize=CGSizeMake(image.size.width/2, image.size.height/2);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(NULL,
thumbSize.width,
thumbSize.height,
8,//bits per component
thumbSize.width*4,
colorSpace,
bitmapInfo);
CGRect drawRect = CGRectMake(0, 0, thumbSize.width, thumbSize.height);
CGContextDrawImage(context, drawRect, image.CGImage);
CGColorSpaceRelease(colorSpace);
//第二步 取每个点的像素值
unsigned char* data = CGBitmapContextGetData (context);
if (data == NULL) return nil;
NSCountedSet *cls=[NSCountedSet setWithCapacity:thumbSize.width*thumbSize.height];
for (int x=0; x<thumbSize.width; x++) {
for (int y=0; y<thumbSize.height; y++) {
int offset = 4*(x*y);
int red = data[offset];
int green = data[offset+1];
int blue = data[offset+2];
int alpha = data[offset+3];
if (alpha>0) {//去除透明
if (red==255 && green==255 && blue==255) {//去除白色
}else{
NSArray *clr=@[@(red),@(green),@(blue),@(alpha)];
[cls addObject:clr];
}
}
}
}
CGContextRelease(context);
//第三步 找到出现次数最多的那个颜色
NSEnumerator *enumerator = [cls objectEnumerator];
NSArray *curColor = nil;
NSArray *MaxColor=nil;
NSUInteger MaxCount=0;
while ( (curColor = [enumerator nextObject]) != nil )
{
NSUInteger tmpCount = [cls countForObject:curColor];
if ( tmpCount < MaxCount ) continue;
MaxCount=tmpCount;
MaxColor=curColor;
}
return [UIColor colorWithRed:([MaxColor[0] intValue]/255.0f) green:([MaxColor[1] intValue]/255.0f) blue:([MaxColor[2] intValue]/255.0f) alpha:([MaxColor[3] intValue]/255.0f)];
}
+ (UIImage *)scaleToSize:(UIImage *)img size:(CGSize)size{
// 创建一个bitmap的context
// 并把它设置成为当前正在使用的context
UIGraphicsBeginImageContext(size);
// 绘制改变大小的图片
[img drawInRect:CGRectMake(0, 0, size.width, size.height)];
// 从当前context中创建一个改变大小后的图片
UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
// 使当前的context出堆栈
UIGraphicsEndImageContext();
// 返回新的改变大小后的图片
return scaledImage;
}
+ (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;
}
//压缩图片到指定大小kb
+ (UIImage *)scaleImage:(UIImage *)image toKb:(NSInteger)kb{
if (!image) {
return image;
}
if (kb<1) {
return image;
}
kb *= 1024;
CGFloat compression = 0.9f;
CGFloat maxCompression = 0.1f;
NSData *imageData = UIImageJPEGRepresentation(image, compression);
NSLog(@"YS-之前大小:%fkb",(float)[imageData length]/1024.0f);
while ([imageData length] > kb && compression > maxCompression) {
compression -= 0.1;
imageData = UIImageJPEGRepresentation(image, compression);
}
NSLog(@"YS-之后大小:%fkb",(float)[imageData length]/1024.0f);
UIImage *compressedImage = [UIImage imageWithData:imageData];
return compressedImage;
}
/**
* 剪切图片为正方形
*
* @param image 原始图片比如size大小为(400x200)pixels
* @param newSize 正方形的size比如400pixels
*
* @return 返回正方形图片(400x400)pixels
*/
- (UIImage *)squareImageFromImage:(UIImage *)image scaledToSize:(CGFloat)newSize {
CGAffineTransform scaleTransform;
CGPoint origin;
if (image.size.width > image.size.height) {
//image原始高度为200,缩放image的高度为400pixels,所以缩放比率为2
CGFloat scaleRatio = newSize / image.size.height;
scaleTransform = CGAffineTransformMakeScale(scaleRatio, scaleRatio);
//设置绘制原始图片的画笔坐标为CGPoint(-100, 0)pixels
origin = CGPointMake(-(image.size.width - image.size.height) / 2.0f, 0);
} else {
CGFloat scaleRatio = newSize / image.size.width;
scaleTransform = CGAffineTransformMakeScale(scaleRatio, scaleRatio);
origin = CGPointMake(0, -(image.size.height - image.size.width) / 2.5f);//2.0
}
CGSize size = CGSizeMake(newSize, newSize);
//创建画板为(400x400)pixels
if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) {
UIGraphicsBeginImageContextWithOptions(size, YES, 0);
} else {
UIGraphicsBeginImageContext(size);
}
CGContextRef context = UIGraphicsGetCurrentContext();
//将image原始图片(400x200)pixels缩放为(800x400)pixels
CGContextConcatCTM(context, scaleTransform);
//origin也会从原始(-100, 0)缩放到(-200, 0)
[image drawAtPoint:origin];
//获取缩放后剪切的image图片
image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
//qie
- (UIImage*)getSubImage:(UIImage *)image mCGRect:(CGRect)mCGRect
centerBool:(BOOL)centerBool {
/*如若centerBool为Yes则是由中心点取mCGRect范围的图片*/
float imgWidth = image.size.width;
float imgHeight = image.size.height;
float viewWidth = mCGRect.size.width;
float viewHidth = mCGRect.size.height;
NSLog(@"cutcut ** %f %f %f %f",imgWidth ,imgHeight,viewWidth,viewHidth);
CGRect rect;
if(centerBool){
rect = CGRectMake((imgWidth-viewWidth)/2,(imgHeight-viewHidth)/2,viewWidth,viewHidth);
}else{
if(viewHidth < viewWidth){
if(imgWidth <= imgHeight){
rect = CGRectMake(0, 0, imgWidth, imgWidth*imgHeight/viewWidth);
}else{
float width = viewWidth*imgHeight/viewHidth;
float x = (imgWidth - width)/2;
if(x > 0){
rect = CGRectMake(x, 0, width, imgHeight);
}else{
rect = CGRectMake(0, 0, imgWidth, imgWidth*viewHidth/viewWidth);
}
}
}else{
if(imgWidth <= imgHeight){
float height = viewHidth*imgWidth/viewWidth;
if(height < imgHeight){
rect = CGRectMake(0,0, imgWidth, height);
}else{
rect = CGRectMake(0,0, viewWidth*imgHeight/viewHidth,imgHeight);
}
}else{
float width = viewWidth * imgHeight / viewHidth;
if(width < imgWidth){
float x = (imgWidth - width)/2;
rect = CGRectMake(x,0,width, imgHeight);
}else{
rect = CGRectMake(0,0,imgWidth, imgHeight);
}
}
}
}
NSLog(@"cutcut %f %f %f %f",rect.origin.x,rect.origin.y,rect.size.width,rect.size.height);
CGImageRef subImageRef = CGImageCreateWithImageInRect(image.CGImage, rect);
CGRect smallBounds = CGRectMake(0,0,CGImageGetWidth(subImageRef),CGImageGetHeight(subImageRef));
UIGraphicsBeginImageContext(smallBounds.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextDrawImage(context, smallBounds, subImageRef);
UIImage *smallImage = [UIImage imageWithCGImage:subImageRef];
UIGraphicsEndImageContext();
return smallImage;
}
- (UIImage*)dx_getSubImage:(UIImage *)image mCGRect:(CGRect)mCGRect {
float imgWidth = image.size.width;
float imgHeight = image.size.height;
float viewWidth = mCGRect.size.width;
float viewHidth = mCGRect.size.height;
float y = mCGRect.origin.y;
NSLog(@"dx_getSubImage 0** %f %f %f %f",imgWidth ,imgHeight,viewWidth,viewHidth);
CGRect rect;
//x3 一点3像素
rect = CGRectMake(0, y, imgWidth*3, viewHidth*3);
NSLog(@"dx_getSubImage 1** %f %f %f %f",rect.origin.x,rect.origin.y,rect.size.width,rect.size.height);
CGImageRef subImageRef = CGImageCreateWithImageInRect(image.CGImage, rect);
CGRect smallBounds = CGRectMake(0,0,CGImageGetWidth(subImageRef),CGImageGetHeight(subImageRef));
UIGraphicsBeginImageContext(smallBounds.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextDrawImage(context, smallBounds, subImageRef);
UIImage *smallImage = [UIImage imageWithCGImage:subImageRef];
UIGraphicsEndImageContext();
return smallImage;
}
+ (instancetype)imageWithOriginalName:(NSString *)imageName
{
UIImage *image = [UIImage imageNamed:imageName];
return [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
}
+ (instancetype)imageWithStretchableName:(NSString *)imageName orginX:(CGFloat)x orginY:(CGFloat)y
{
UIImage *image = [UIImage imageNamed:imageName];
return [image stretchableImageWithLeftCapWidth:x topCapHeight:y];
}
+(UIImage*)createImageWithColor:(UIColor*) color
{
CGRect rect=CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, rect);
UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return theImage;
}
@end