L'ho effettuato sotto la funzione fitImage
che accetta uno UIImage
e uno CGSize
. Nel caso in cui l'immagine di input sia più grande della casella di input, l'immagine verrà ridimensionata per riempire il riquadro. Se la scatola e l'immagine non hanno lo stesso rapporto, l'immagine non riempie completamente la scatola e ci sarà uno sfondo visibile. In questo caso questo sfondo è sempre bianco. Come posso cambiare questo ad es. uno sfondo nero?UIImmagine: riempire lo sfondo
+ (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;
}
Per favore dimmi se hai bisogno di ulteriori informazioni.
Soluzione:
+ (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;
}
Grazie weichsel! – dhrm