Duck
Duck

Reputation: 36013

Cocos2D 2.0 - changing the rect of a CCSprite / stretching a sprite

I have created an atlas with all images I will use in a class. If this was a sprite created from an image, I would create it like

mySprite = [CCSprite spriteWithFile:@"white.png" rect:frame];

"white.png" is a 1x1 pixel image that I am stretching to cover the entire CCSprite size, that is defined by rect:frame on that API.

But in order to optimize I/O and memory, I put white.png in an atlas and my idea was to create it using

mySprite = [CCSprite spriteWithSpriteFrameName:@"white.png"];

but this will create a 1x1 pixel sprite. So, my idea was to create a category to extend CCSprite with these lines

@implementation CCSprite (CCSprite_Resize)


-(void)resizeTo:(CGSize) theSize
{
    CGFloat newWidth = theSize.width;
    CGFloat newHeight = theSize.height;


    float startWidth = self.contentSize.width;
    float startHeight = self.contentSize.height;

    float newScaleX = newWidth/startWidth;
    float newScaleY = newHeight/startHeight;

    self.scaleX = newScaleX;
    self.scaleY = newScaleY;

}

so I could do this

mySprite = [CCSprite spriteWithSpriteFrameName:@"white.png"];
[mySprite resizeTo:frame.size];

and the 1x1 sprite would be stretched to cover the size I want.

The problem is that this is not working.

any clues? thanks.

Upvotes: 0

Views: 3197

Answers (2)

SentineL
SentineL

Reputation: 4732

Make shore you are not overriding somthing like - (CGAffineTransform)nodeToParentTransform. I'm using Box2d physics with cocos2d, and provided be template class PhysicsSprite (subclass of CCSprite) overrided it, and there was a bug: scale property didn't change anything. I fixed it like this:

- (CGAffineTransform)nodeToParentTransform
{
    b2Vec2 pos = body_->GetPosition();

    float x = pos.x * PTM_RATIO;
    float y = pos.y * PTM_RATIO;

    // Make matrix
    float radians = body_->GetAngle();
    float c = cosf(radians);
    float s = sinf(radians);

    if (!CGPointEqualToPoint(anchorPointInPoints_, CGPointZero))
    {
        x += c * -anchorPointInPoints_.x * scaleX_ + -s * -anchorPointInPoints_.y * scaleY_;
        y += s * -anchorPointInPoints_.x * scaleX_ + c * -anchorPointInPoints_.y * scaleY_;
    }

    // Rot, Translate Matrix
    transform_ = CGAffineTransformMake( c * scaleX_, s * scaleX_,
    -s * scaleY_, c * scaleY_,
    x, y );

    return transform_;
}

In original, there was no scaleX_ and scaleY_ multiplying.

Upvotes: 2

Morion
Morion

Reputation: 10860

It seems that in your case you can use CCLayerColor to create one-color layer. There is no need to use sprite for it.

About your question - make sure, that frame.size is not zero (CGSizeZero)

Upvotes: 0

Related Questions