Установить кадр 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;
}

person hemant    schedule 30.05.2013    source источник


Ответы (2)


Вы можете масштабировать 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;
person Kreiri    schedule 30.05.2013

Вы можете добавить собственный класс, скажем, 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
person IronMan    schedule 30.05.2013