2017年12月5日 星期二

正方形圖片

+ (UIImage *)resizeToSquareImageWithImage:(UIImage*)image toSize:(CGSize)newSize
{
    // crop image to square one
    CGSize oldSize = image.size;
    double newWidth = oldSize.width > oldSize.height ? oldSize.height : oldSize.width;
    CGRect newRect = CGRectMake(0.0, 0.0, newWidth, newWidth);

    CGImageRef sourceImageRef = [image CGImage];
    CGImageRef newImageRef = CGImageCreateWithImageInRect(sourceImageRef, newRect);
    UIImage *squareImage = [UIImage imageWithCGImage:newImageRef];
    CGImageRelease(newImageRef);
    // resize the image
    UIGraphicsBeginImageContext(newSize);
    [squareImage drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
  
    return newImage;
}

沒有留言:

張貼留言