我有一张图像,我想用 CCSprite 以不同的尺寸显示。我通常知道 CCSprite 只添加图像宽度和高度的图像,但我想知道是否有任何方法,所以我不必先手动缩放图像,如下所示,然后将图像提供给 ccpsrite?
-(UIImage*)imageByScalingAndCroppingForSize:(CGSize)targetSize image:(UIImage*)sourceImage
{
UIImage *newImage = sourceImage;
CGSize imageSize = sourceImage.size;
/// Source image is of desired size or desired size 0x0, no change is done
if (!CGSizeEqualToSize(targetSize, CGSizeZero) && !CGSizeEqualToSize(imageSize, targetSize))
{
CGFloat aspectRatio = imageSize.width / imageSize.height;
CGFloat newAspectRatio = targetSize.width / targetSize.height;
CGSize tempSize = targetSize;
if (newAspectRatio < aspectRatio)
{
tempSize.width = targetSize.width * aspectRatio / newAspectRatio;
}
else
{
tempSize.height = targetSize.height * newAspectRatio / aspectRatio;
}
UIGraphicsBeginImageContext(targetSize);
[sourceImage drawInRect:CGRectMake((targetSize.width - tempSize.width) / 2.0, (targetSize.height - tempSize.height) / 2.0, tempSize.width, tempSize.height)];
newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
}
return newImage;
}