test.png (像素 20*20) test@2x.png(像素40*40) test@3x.png(像素 60*60)
UIImage *image = [UIImageimageNamed:@"test.png"];
image.size输出大小为(20,20);
UIImage *image = [UIImage imageNamed:@"test@2x.png"];
image.size输出大小为(20,20);
UIImage *image = [UIImage imageNamed:@"test@3x.png"];
image.size输出大小为(20,20);
image.size输出的大小会自动识别图片是几倍的,如果是3倍的输出的结果就是像素除以3,2倍的像素除以2,image.size在图片处理时会很有用,例如下面 CGImageRef,里面的CGRectMake取得是图片像素的大小,如果:代码:
UIImage *image = [UIImage imageNamed:@"test@2x.png"];
CGImageRef ref = CGImageCreateWithImageInRect([imageCGImage], CGRectMake(0,0, image.size.width, image.size.height));
ref 得到的就是test@2x.png这张图片左上角的四分之一大小
正确做法应该是:
UIImage *image = [UIImage imageNamed:@"test.png"];
CGImageRef imageRef = [image CGImage];
CGSize size = CGSizeMake(CGImageGetWidth(imageRef), CGImageGetHeight(imageRef));//这个size就是实际图片的像素大小
CGImageRef ref = CGImageCreateWithImageInRect([image CGImage], CGRectMake(0, 0, size.width, size.height));//这里的rect切割是按图片的像素切割
UIGraphicsBeginImageContextWithOptions(CGSizeMake(size.width, size.height), NO, 0);//最终获取得到的画布大小
CGContextRef con = UIGraphicsGetCurrentContext();
CGContextDrawImage(con, CGRectMake(0, 0, size.width, size.height), ref);
// UIImage *ima = [UIImage imageWithCGImage:ref];
UIImage *ima = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();