1

I'm trying to set a background image for a CCButton and make sure it stretches or minimizes to the exact size of the CCButton:

-(void)setBackgroundSpriteFrame: (NSString*)spriteFrameFileName
{
    NSString* fullFileName = [NSString stringWithFormat:@"%@.png", spriteFrameFileName];
    CCSpriteFrame *spriteFrame = [CCSpriteFrame frameWithImageNamed:fullFileName];
    [super setBackgroundSpriteFrame:spriteFrame forState:CCControlStateNormal];
    double scaleValue = self.contentSize.height / spriteFrame.rect.size.height;
    [self.background setScale:scaleValue];
    self.fileName = spriteFrameFileName;
}

This method resides inside a class that inherits from CCButton.

The problem is that I see the background image but it is squeezed in a weird way (see image) and not minimized\stretched to the size of the button.

Please note that the image and the button are squares so no need to scale X\Y separately, and also note that the CCButton is generated with SprtieBuilder and not by code.

'Weird look':
The square image got a weird squeezed look
Original look:
Original image

Thanks

Loves2Develop
  • 774
  • 1
  • 8
  • 29
  • cant judge 'weird' ... could you show the actual background texture ? I am assuming that the pic above is the rendered CCButton. – YvesLeBorg Sep 21 '15 at 15:32

2 Answers2

1

Thanks 'YvesLeBorg' for trying to help, I managed to solve this issue.

I'm posting the code that helped me. Hope it will help others.

NSString* fullFileName = [NSString stringWithFormat:@"%@.png", spriteFrameFileName];
CCTexture *texture = [CCTexture textureWithFile:fullFileName];
texture.contentScale = 2.0;
[super setBackgroundSpriteFrame:[texture createSpriteFrame] forState:CCControlStateNormal];
[self setScale:0.40];
self.fileName = spriteFrameFileName;
Loves2Develop
  • 774
  • 1
  • 8
  • 29
0

Have not enough reputation to comment, so please excuse to write an answer instead.

When I encountered the same problem I found a net solution on the cocos2d forum (no link, sry). Summarizing it - there is no need to scale the image separately. But one shall follow 2 rules:

1) the image should be at least same size than the element (CCButton) and

2) not forget to explicitly set the forState:CCControlStateNormal

the usage of contentScale as you did is not needed in that case.