UIImage使用总结

1.UIImage的scale

有两个图片,a.png的大小为36*36;a@2x.png大小为72*72。在代码中载入a.png,如果是普通屏幕(320*480),默认会使用a.png,其scale为1;如果是高分屏(640*960),默认会使用a@2x.png,但是其逻辑大小变成36*36,此时scale为2。因此,图像的实际的尺寸(像素)等于image.size乘以image.scale。

UIScreen的scale。

逻辑坐标(单位是point)和设备坐标(单位是pixel)。

2.获取屏幕上的UIImage

1.图片绘制到context,然后从context获取图片。

    UIBarButtonItem *item = [self.toolBar.items objectAtIndex:0];
    
    for (UIView *subView in [item.customView subviews]) {//遍历这个view的subViews
        if ([subView isKindOfClass:NSClassFromString(@"UIImageView")] || [subView isKindOfClass:NSClassFromString(@"UIThreePartButton")]) {//找到自己需要的subView
            
            if(UIGraphicsBeginImageContextWithOptions != NULL)
            {
                UIGraphicsBeginImageContextWithOptions(subView.frame.size, NO, 0.0);
            } else {
                UIGraphicsBeginImageContext(subView.frame.size);
            }            
            
            //获取图像
            [subView.layer renderInContext:UIGraphicsGetCurrentContext()];
            UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
        }

2.直接通过UIImageView的image属性获取。

image = [subView image];

3.自己在content上绘制图像返回图片。

- (UIImage*)dotImageWithColor:(UIColor *)color{
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(8, 8), NO, 0);
    CGContextRef context = UIGraphicsGetCurrentContext();
    [color setFill];
    UIBezierPath *tPath = [UIBezierPath bezierPathWithArcCenter:CGPointMake(4, 4) radius:4 startAngle:-M_PI endAngle:M_PI clockwise:NO];
    [tPath fill];
    UIImage *dotImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return dotImage;
}

3.储存图片

1.保存到手机相册。调用UIImageWriteToSavedPhotosAlbum函数。

CGImageRef screen = UIGetScreenImage();
UIImage* image = [UIImage imageWithCGImage:screen];
CGImageRelease(screen);
UIImageWriteToSavedPhotosAlbum(image, self, nil, nil);

2.保存到APP。先把图片转换成PNG或者JPEG格式的NSData,然后writeToFile。

- (BOOL)writeImage:(UIImage*)image toFileAtPath:(NSString*)aPath
{
    //NSString  *jpgPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Test.jpg"];
    
    if ((image == nil) || (aPath == nil) || ([aPath isEqualToString:@""]))
        return NO;
    @try{
        NSData *imageData = nil;
        NSString *ext = [aPath pathExtension];
        if ([ext isEqualToString:@"png"]){
            imageData = UIImagePNGRepresentation(image);
        }
        else{
            // the rest, we write to jpeg
            // 0. best, 1. lost. about compress.
            imageData = UIImageJPEGRepresentation(image, 0);
        }
        if ((imageData == nil) || ([imageData length] <= 0))
            return NO;
        [imageData writeToFile:aPath atomically:YES];
        return YES;
    }
    @catch (NSException *e){
        NSLog(@"create thumbnail exception.");
    }
    return NO;
}

4.图片放大缩小

1.在指定大小的content里重绘图片(自定义图片的长宽与此方法类似)。

- (UIImage *)scaleImage:(UIImage *)image toScale:(float)scaleSize{
    UIGraphicsBeginImageContext(CGSizeMake(image.size.width * scaleSize, image.size.height * scaleSize);
    [image drawInRect:CGRectMake(0, 0, image.size.width * scaleSize, image.size.height * scaleSize)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}

 2.初始化时使用如下方法。 scale参数指定缩放比例。orientation参数是枚举值,可以对图片进行旋转。

- (instancetype)initWithCGImage:(CGImageRef)cgImage scale:(CGFloat)scale orientation:(UIImageOrientation)orientation NS_AVAILABLE_IOS(4_0);

 5.模糊图片

    UIImage *screenshot = [UIImage screenshot];
    NSData *imageData = UIImageJPEGRepresentation(screenshot, .1);
    UIImage *blurredSnapshot = [[UIImage imageWithData:imageData] blurredImage:0.6];

其中,screenshot方法实现如下(加入了对屏幕旋转的操作?) 

#import "UIImage+Screenshot.h"

@implementation UIImage (Screenshot)

+ (UIImage *)screenshot
{
    CGSize imageSize = [[UIScreen mainScreen] bounds].size;
 
    if (NULL != UIGraphicsBeginImageContextWithOptions) {
        UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0);
    } else {
        UIGraphicsBeginImageContext(imageSize);
    }
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    for (UIWindow *window in [[UIApplication sharedApplication] windows]) {
        if (![window respondsToSelector:@selector(screen)] || [window screen] == [UIScreen mainScreen]) {
            CGContextSaveGState(context);

            CGContextTranslateCTM(context, [window center].x, [window center].y);

            CGContextConcatCTM(context, [window transform]);
            
            CGContextTranslateCTM(context,
                                  -[window bounds].size.width * [[window layer] anchorPoint].x,
                                  -[window bounds].size.height * [[window layer] anchorPoint].y);
            
            [[window layer] renderInContext:context];
            
            CGContextRestoreGState(context);
        }
    }
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return image;
}

@end

6.设置UIImage的渲染模式:UIImage.renderingMode

着色(Tint Color)是iOS7界面中的一个重大改变,你可以设置一个UIImage在渲染时是否使用当前视图的Tint Color。UIImage新增了一个只读属性:renderingMode,对应的还有一个新增方 法:imageWithRenderingMode:,它使用UIImageRenderingMode枚举值来设置图片的renderingMode属 性。该枚举中包含下列值:

UIImageRenderingModeAutomatic // 根据图片的使用环境和所处的绘图上下文自动调整渲染模式。 
UIImageRenderingModeAlwaysOriginal // 始终绘制图片原始状态,不使用Tint Color。 
UIImageRenderingModeAlwaysTemplate // 始终根据Tint Color绘制图片,忽略图片的颜色信息。 

renderingMode属性的默认值是UIImageRenderingModeAutomatic,即UIImage是否使用Tint Color取决于它显示的位置。其他情况可以看下面的图例

以下的代码说明了使用一个既定的rendering模式创建图片是多么简单:

UIImage *img = [UIImage imageNamed:@"myimage"]; 
img = [img imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];

 By default, an image (UIImage) is created with UIImageRenderingModeAutomatic. If you have UIImageRenderingModeAutomatic set on your image, it will be treated as template or original based on its context. Certain UIKit elements—including navigation bars, tab bars, toolbars, segmented controls—automatically treat their foreground images as templates, although their background images are treated as original. Other elements—such as image views and web views—treat their images as originals. If you want your image to always be treated as a template regardless of context, set UIImageRenderingModeAlwaysTemplate; if you want your image to always be treated as original, set UIImageRenderingModeAlwaysOriginal.

x.链接

IOS:聊一聊UIImage几点知识

UIImage的scale是什么?

原文地址:https://www.cnblogs.com/zhongriqianqian/p/3977731.html