2013年3月27日 星期三

[iOS]將UIimage的圖片縮小



調整UIImage Size,方便縮圖使用。

呼叫:

UIImage* image =[self imageWithImageSimple:image scaledToSize:CGSizeMake(512.0, 512.0)];//縮小至512X512


函式:

//照片縮小 image,最大寬高
- (UIImage*)imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize)newSize
{   
    float width,height;
    if (image.size.width<newSize.width && image.size.height<newSize.height){
        //如果已經小於newSize則不縮小
        width=image.size.width;
        height=image.size.height;
    }else if (image.size.height >= (newSize.height/newSize.width)*image.size.width){
        width=image.size.width/image.size.height*newSize.height;
        height=newSize.height;
    }else{
        height=image.size.height/image.size.width*newSize.height;
        width=newSize.width;
    }
    newSize.width=width;
    newSize.height=height;
    // Create a graphics image context
    UIGraphicsBeginImageContext(newSize);
    // Tell the old image to draw in this new context, with the desired
    // new size
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    // Get the new image from the context
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    // End the context
    UIGraphicsEndImageContext();
    // Return the new image.
    return newImage;
}