标签:
说到sprite的自动拉伸,可能有人的第一感觉是Scale9Sprite,但其实Scale9Sprite有其独特的使用场合的,即四角不变形,而且比较重,耗费内存较多。对于简单的拉伸,比如对纯色的图片进行拉伸,杀鸡焉用牛刀乎?用Sprite就足够了。
先看别人的一个简单的Sprite自动拉伸全屏例子(来源):
Size size = Director::getInstance()->getWinSize(); Sprite* bg = Sprite::create("bg.png"); bg->setPosition(Vec2(size.width/2, size.height/2)); float winw = size.width; //获取屏幕宽度 float winh = size.height;//获取屏幕高度 float spx = bg->getTextureRect().getMaxX(); float spy = bg->getTextureRect().getMaxY(); bg->setScaleX(winw/spx); //设置精灵宽度缩放比例 bg->setScaleY(winh/spy);
啰啰嗦嗦的还是有点麻烦,若想简化,关键在于充分利用CCSprite的另一个create方法
static Sprite* create(const std::string& filename, const Rect& rect);
改写后的方法:
Rect rect = Rect::ZERO; rect.size = Director::getInstance()->getWinSize(); Sprite* bg = Sprite::create("bg.png", rect); bg->setColor(Color3B(178, 178, 178)); bg->setAnchorPoint(Vec2(0, 0)); addChild(bg);
我们还可以用它来实现一条简单的分隔线或横线:
Rect rect = Rect::ZERO; rect.size = Size(Width, Height); auto glview = cocos2d::Director::getInstance()->getOpenGLView(); float scaleY = glview->getScaleY(); rect.size.height = 1.0/scaleY; Sprite* separateLine = Sprite::create("bg.png", rect); separateLine->setAnchorPoint(Vec2(0, 0)); separateLine->setColor(Color3B(178, 178, 178)); addChild(separateLine);
标签:
原文地址:http://my.oschina.net/ioslighter/blog/373539