需要使用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;
}
可以調整CCSprite. CCSprite是CCNode的子類,CCNode有這些屬性:
/** The scale factor of the node. 1.0 is the default scale factor. It modifies the X and Y scale at the same time. */
@property(nonatomic,readwrite,assign) float scale;
/** The scale factor of the node. 1.0 is the default scale factor. It only modifies the X scale factor. */
@property(nonatomic,readwrite,assign) float scaleX;
/** The scale factor of the node. 1.0 is the default scale factor. It only modifies the Y scale factor. */
@property(nonatomic,readwrite,assign) float scaleY;