Hi, guys!
I’m searching for the way to scale texture to the size of sprite containing it.
Let’s me describe my case.
I’m have some file “ShopIcon.png” with 80x80 size.
I’m load this file into the Sprite:
var shopIcon = new cc.Sprite(“resources/ShopIcon.png”);
Next, I check content size of my sprite:
var iconSize = shopIcon.getContentSize();
All fine, it returns:
Point[80,80]
Next, I want to resize my sprite to size of parent panel which have size 100x100.
So, I just do it:
shopIcon.width = 100;
shopIcon.height = 100;
Well, sprite container has been resized properly. Now, it has size 100x100:
var newIconSize = shopIcon.getContentSize();
returns:
Point[100,100]
However, my texture is not stretch to the size of parent sprite.
It’s still located at the point x = 0, y = 0 of sprite container and it has size 80x80.
So, I have some solutions to such issue for now:
-
The most stupid way: just store the same texture in different sizes. So, I will have “ShopIcon_Panel80x80.png”, “ShopIcon_Window120x120.png”, etc.
I think you can see the problems with such approach. -
Scale image manually on each resize call:
function resizeSprite(sprite, width, height) {
sprite.width = width;
sprite.height = height;
sprite.setScale(width / sprite.getTextureRect().width, height / sprite.getTextureRect().height);
}
I think it can be good in most cases but now it’s difficult to scale sprites without breaking texture stretching.
In addittion, it’s difficult to understand, what does it mean “set the scale of sprite to 1”. Does this mean: we should scale a sprite to size of it’s texture, or we should scale a sprite to it’s original size?
- Using Scale9Sprite instead of Sprite:
We just change:
var shopIcon = new cc.Sprite(“resources/ShopIcon.png”);
to:
var shopIcon = new cc.Scale9Sprite(“resources/ShopIcon.png”);
… and all next code works as expected.
For now, I think it’s the best approach, but there are some potential problems with it:
a) now we have dependency from cocos extensions library; so the resulting JS code will be have larger size; it may be unacceptably for little games with high requirements to loading time;
b) 9-scale mechanism looks ugly for some little values:
https://pasteboard.co/images/HyeF8cy.png/download
It’s a default Cocos image logo stretched to 30x30 size.
I believe such problem may be resolved with properly capInsets params, isn’t it?
so…
c) we should provide 9-pitch scale settings for each image to preserves it aspect ratio while scaling
What I actually wanted when I just encountered with such problem:
I’m just add texture to my Sprite and it’s automagically stretches to Sprite size on each resizing operation.
Maybe, there are some options to control stretch strategy for texture (something like fill options (fillType/fillCenter/fillStart/…) that are presents in Sprite class of Cocos Creator Engine).
So, does anyone know how to achieve described behavior with Sprite class?
Any suggestions will be helpful.