6
fitImage
の機能はUIImage
となり、CGSize
となりました。入力画像が入力ボックスより大きい場合、画像はボックスに入力されるように縮小されます。ボックスと画像の比率が同じでない場合、画像はボックス全体を満たしませんし、背景も見えます。この場合、この背景は常に白です。これをどのように変更できますか?黒い背景?UIImage:背景を記入してください
+ (UIImage*) fitImage:(UIImage*)image inBox:(CGSize)size {
if (image.size.width==size.width && image.size.height==size.height)
return image;
if (image.size.width<size.width && image.size.height<size.height)
return [Util scaleImage:image toSize:size];
float widthFactor = size.width/image.size.width;
float heightFactor = size.height/image.size.height;
CGSize scaledSize = size;
if (widthFactor<heightFactor) {
scaledSize.width = size.width;
scaledSize.height = image.size.height * widthFactor;
} else {
scaledSize.width = image.size.width * heightFactor;
scaledSize.height = size.height;
}
UIGraphicsBeginImageContextWithOptions(size, NO, 0.0);
float marginX = (size.width-scaledSize.width)/2;
float marginY = (size.height-scaledSize.height)/2;
CGRect scaledImageRect = CGRectMake(marginX, marginY, scaledSize.width, scaledSize.height);
[image drawInRect:scaledImageRect];
UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return scaledImage;
}
さらに詳しい情報が必要な場合は教えてください。
ソリューション:
+ (UIImage*) fitImage:(UIImage*)image inBox:(CGSize)size withBackground:(UIColor*)color {
if (image.size.width==size.width && image.size.height==size.height)
return image;
if (image.size.width<size.width && image.size.height<size.height)
return [Util scaleImage:image toSize:size];
float widthFactor = size.width/image.size.width;
float heightFactor = size.height/image.size.height;
CGSize scaledSize = size;
if (widthFactor<heightFactor) {
scaledSize.width = size.width;
scaledSize.height = image.size.height * widthFactor;
} else {
scaledSize.width = image.size.width * heightFactor;
scaledSize.height = size.height;
}
UIGraphicsBeginImageContextWithOptions(size, NO, 0.0);
float marginX = (size.width-scaledSize.width)/2;
float marginY = (size.height-scaledSize.height)/2;
CGRect scaledImageRect = CGRectMake(marginX, marginY, scaledSize.width, scaledSize.height);
UIImage* temp = UIGraphicsGetImageFromCurrentImageContext();
[color set];
UIRectFill(CGRectMake(0.0, 0.0, temp.size.width, temp.size.height));
[image drawInRect:scaledImageRect];
UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return scaledImage;
}
ありがとうございました! – dhrm