动态缩放图片,剪裁指定位置大小


- (void)viewDidLoad
{
    [super viewDidLoad];
    
    UIImageView *imgView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 50, 320, 320)];
    imgView.backgroundColor = [UIColor yellowColor];
    imgView.image = [self shearPng:[UIImage imageNamed:@"111.jpg"]];
    
    [self.view addSubview:imgView];
}

- (UIImage *)shearPng:(UIImage *)png{
    
    CGSize size = png.size;
    CGFloat scale = 1.0;
    
    if (size.height<640.0 || size.width < 640.0) {
        scale = 640.0/size.width > 640.0/size.height ? 640.0/size.width : 640.0/size.height;
    }
    
    UIImage *scaleImg = [self scaleToSize:png size:CGSizeMake(size.width*scale, size.height*scale)];
    
    UIImage *backImage = [self shearPngWithScaleImg:scaleImg];
    
    return backImage;
}

- (UIImage *)shearPngWithScaleImg:(UIImage *)png{
    
    CGFloat x=0.0;
    CGFloat y=0.0;
    
    if (png.size.width > 640) {
        x = (png.size.width - 640)/2.0;
    }
    
    if (png.size.height > 640) {
        y = (png.size.height - 640)/2.0;
    }
    
    CGImageRef imageRef = CGImageCreateWithImageInRect(png.CGImage, CGRectMake(x, y, 640, 640));
    
    UIImage *scaledImage = [UIImage imageWithCGImage:imageRef];
    CGImageRelease(imageRef);
    
    // 返回新的改变大小后的图片
    return scaledImage;
}

- (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;
}

你可能感兴趣的:(ios,uiimage,CGImageRef,剪裁图片,图片指定大小)