关于uiimage的比例缩放、及图片截取

之前一直说要把瀑布流发上来、样子已经出来了。是用table+scroll写的。不过工作比较忙  所以暂时停下了。再过些日子吧

这篇是一个记录。

实现:选取任意一张宽高比不同的图片。显示在269*88的一个IMAGEVIEW上面。并且不会出现比例失调


//269*88 要显示的大小
    CGSize reSize = CGSizeMake(269.0, 88.0);
    //得到最后绘出来的图片大小
    image = [self scaleImage:image toScale:reSize];



//1.缩放
- (UIImage *)zoomImage:(UIImage *)image toScale:(CGSize)reSize
{
    //根据要显示的大小等比例算出缩放后的图片大小
    NSLog(@"image=====w==%f\n--------image==%f\n\n",image.size.width,image.size.height);
    ZoomInEqualPercent *ziep = [[ZoomInEqualPercent alloc] init];
    CGSize size_max = CGSizeMake(reSize.width, reSize.height);
    CGSize size_new =  [ziep zoomSizeWithMin:image.size :size_max];
    NSLog(@"size_new=====w==%f\n--------h==%f\n\n",size_new.width,size_new.height);
    //绘制这个大小的图片
    UIGraphicsBeginImageContext(size_new);
    [image drawInRect:CGRectMake(0,0, size_new.width, size_new.height)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    NSLog(@"scaledImage=====w==%f\n--------scaledImage==%f\n\n",scaledImage.size.width,scaledImage.size.height);
    
    return scaledImage;
}

- (UIImage *)scaleImage:(UIImage *)image toScale:(CGSize)reSize
{

//先按要显示的大小 去比例缩放下图片

UIImage *scaledImage = [self zoomImage:image toScale:reSize];

//计算截取位置。这里我们考虑一般拍照边界位置可能存在全白或全黑的情况,多数重要的会在中间位置。所以计算下截取是重绘图片的中间位置

float drawW = 0.0; float drawH = 0.0; CGSize size_new = scaledImage.size; if (size_new.width > reSize.width) { drawW = (size_new.width - reSize.width)/2.0; } if (size_new.height > reSize.height) { drawH = (size_new.height - reSize.height)/2.0; } NSLog(@"drawW=====w==%f\n--------drawH==%f\n\n",drawW,drawH); //截取截取大小为需要显示的大小。取图片中间位置截取 CGRect myImageRect = CGRectMake(drawW, drawH, reSize.width, reSize.height); UIImage* bigImage= scaledImage; scaledImage = nil; CGImageRef imageRef = bigImage.CGImage; CGImageRef subImageRef = CGImageCreateWithImageInRect(imageRef, myImageRect); UIGraphicsBeginImageContext(reSize); CGContextRef context = UIGraphicsGetCurrentContext(); CGContextDrawImage(context, myImageRect, subImageRef); UIImage* smallImage = [UIImage imageWithCGImage:subImageRef]; UIGraphicsEndImageContext(); return smallImage; }


你可能感兴趣的:(关于uiimage的比例缩放、及图片截取)