//This method will resize the original image to desired width
//maintaining the Aspect Ratio
-(UIImage*)getResizedToWidth:(CGFloat)width
{
UIImage *resultImage = nil;
CGFloat ar = self.size.width/self.size.height;
CGFloat ht = width/ar;
CGSize newSize = CGSizeMake(width, ht);
UIGraphicsBeginImageContext(newSize);
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextScaleCTM(ctx, 1, -1);
CGContextTranslateCTM(ctx, 0, -newSize.height);
CGRect imageRect = CGRectMake(0, 0, newSize.width, newSize.height);
CGContextDrawImage(ctx, imageRect, self.CGImage);
resultImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return resultImage;
}
//This method will resize the original image to desired height
//maintaining the Aspect Ratio
-(UIImage*)getResizedToHeight:(CGFloat)height
{
UIImage *resultImage = nil;
CGFloat ar = self.size.width/self.size.height;
CGFloat wd = height*ar;
CGSize newSize = CGSizeMake(wd, height);
UIGraphicsBeginImageContext(newSize);
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextScaleCTM(ctx, 1, -1);
CGContextTranslateCTM(ctx, 0, -newSize.height);
CGRect imageRect = CGRectMake(0, 0, newSize.width, newSize.height);
CGContextDrawImage(ctx, imageRect, self.CGImage);
resultImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return resultImage;
}
//This method will take in the maxSizeLength and automatically
// detect the maximum side in image and reduce it to given
// maxSideLength maintaining the Aspect Ratio
-(UIImage*)getResizedMaxSideToLength:(CGFloat)maxSideLength
{
UIImage *src = [UIImage imageWithCGImage:self.CGImage];
if (src.size.width > maxSideLength)
{
src = [src getResizedToWidth:maxSideLength];
}
else
if (src.size.height >= maxSideLength )
{
src = [src getResizedToHeight:maxSideLength];
}
return src;
}
CGImage が必要な場合は、以下のように任意の UIImage の CGImage プロパティにアクセスして取得します。
CGImage *myCGImage = myUIImage.CGImage;