需要使用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;
}