设置CCSprite的框架?

时间:2013-05-30 13:29:41

标签: iphone ios cocos2d-iphone ccsprite

我有一个图像,我希望用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;
}

2 个答案:

答案 0 :(得分:0)

您可以扩展CCSpriteCCSpriteCCNode的子类,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;

答案 1 :(得分: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