0

我有一张图像,我想用 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;
}
4

2 回答 2

0

您可以扩展您的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;
于 2013-05-30T13:42:03.780 回答
0

您可以添加一个自定义类,比如 FlexSprite 并执行此操作

在 FlexSprite.h 中

@interface FlexSprite : CCSprite

+(FlexSprite*)spriteWithFile:(NSString *)imageName frame:(CGSize )size;
-(id)initWithFile:(NSString *)imageName frame:(CGSize )size;
@end

在 FlexSprite.m 中

#import "FlexSprite.h"
@implementation FlexSprite
-(id)initWithFile:(NSString *)imageName frame:(CGSize )size{
    self = [super initWithFile:imageName];
    if (self) {
        self.scaleX = size.width/self.contentSize.width;
        self.scaleY = size.height/self.contentSize.height;
    }
    return self;
}

+(FlexSprite *)spriteWithFile:(NSString *)imageName frame:(CGSize )size{
    return [[[self alloc]initWithFile:imageName frame:size]autorelease];
}

@end
于 2013-05-30T15:04:41.463 回答