Question

I have a image which i would like to show in different sizes with a CCSprite. i know normally a CCSprite adds a image witf width height of image only but i was wondering if there was any method so i don't have to manually scale the image first like as follows and then giving the image to a 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;
}
Was it helpful?

Solution

You can scale your CCSprite. CCSprite is a subclass of CCNode, and CCNode has these properties:

/** 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;

OTHER TIPS

You can add a custom class say FlexSprite and do this

in FlexSprite.h

@interface FlexSprite : CCSprite

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

in 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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top