我有一個640x480像素的圖像,我需要裁剪並將它置於596x596 px UIImage中。任何空白空間都應該是黑色的(它應該在圖像上方和下方黑色)。現在,我種植像這樣......如何在iOS的CGContext中顯示黑色的空白空間
-(UIImage*)cropImage:(UIImage *)theImage toFitSize:(CGSize)theSize
{
CGFloat CROP_X = floorf((theImage.size.width-theSize.width)/2);
CGFloat CROP_Y = floorf((theImage.size.height-theSize.height)/2);
CGRect imageRect = CGRectMake(CROP_X, CROP_Y, theSize.width, theSize.height);
UIGraphicsBeginImageContext(imageRect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetRGBFillColor(context, 0, 0, 0, 1);
CGRect drawRect = CGRectMake(-imageRect.origin.x, -imageRect.origin.y, theImage.size.width, theImage.size.height);
CGContextClipToRect(context, CGRectMake(0, 0, imageRect.size.width, imageRect.size.height));
[theImage drawInRect:drawRect];
UIImage *finalImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return finalImage;
}
而且我也試過
- (UIImage *)croppedImage:(CGRect)bounds
{
CGImageRef imageRef = CGImageCreateWithImageInRect([self CGImage], bounds);
UIImage *croppedImage = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
return croppedImage;
}
但空空間出來爲透明。我該怎麼做呢?
謝謝
真棒!我將contentMode更改爲UIViewContentModeScaleAspectFit,因爲我將圖像保存爲視網膜大小,但以正常大小顯示。謝謝! –