理论基础
显示图片的小控件,继承自 Widget 。
代码实践
static ImageView * create()
创建一个空的ImageView
static ImageView * create(const std::string &imageFileName, //纹理的文件名字。
TextureResType texType=TextureResType::LOCAL)
根据图片名字创建一个ImageView。
void loadTexture (const std::string &fileName, //纹理的文件名字。
TextureResType texType=TextureResType::LOCAL)
为ImageView对象加载纹理
void setTextureRect (const Rect &rect)
更新ImageView纹理矩形的点 它将调用setTextureRect:rotated:untrimmedSize,rotated默认为No,utrimmedSize默认为rect.size
void setScale9Enabled (bool enabled)
开启scale9渲染模式
bool isScale9Enabled () const
查询是否开启了scale9渲染
void setCapInsets (const Rect &capInsets)
设置ImageView的capInsets 只会影响开启了scale9渲染模式的ImageView setScale9Enabled(true)
const Rect & getCapInsets () const
获取ImageView的capInsets尺寸
virtual void ignoreContentAdaptWithSize (bool ignore) override
设置是否忽略用户定义通过setContentSize设定的控件尺寸。 设置为true将忽略用户定义的尺寸,意味着控件尺寸永远等于getVirtualRendererSize的返回值。
实例:
// Create the imageview ImageView* imageView = ImageView::create("cocosui/ccicon.png"); imageView->setPosition(Vec2(widgetSize.width / 2.0f, widgetSize.height / 2.0f)); _uiLayer->addChild(imageView);
// Create the imageview ImageView* imageView = ImageView::create("cocosui/ccicon.png"); imageView->ignoreContentAdaptWithSize(false); imageView->setScale9Enabled(true); imageView->setContentSize(Size(100, 100)); imageView->setCapInsets(Rect(20,20,20,20)); imageView->setPosition(Vec2(widgetSize.width / 2.0f, widgetSize.height / 2.0f)); imageView->setTouchEnabled(true); imageView->addTouchEventListener([=](Ref* sender, Widget::TouchEventType type){ if (type == Widget::TouchEventType::ENDED) { if (imageView->isScale9Enabled()) { imageView->setScale9Enabled(false); } else imageView->setScale9Enabled(true); } });
// Create the imageview ImageView* imageView = ImageView::create("blocks9r.png", Widget::TextureResType::PLIST); imageView->setScale9Enabled(true); imageView->setContentSize(Size(250, 115)); imageView->setFlippedX(true); imageView->setScale(0.5); imageView->ignoreContentAdaptWithSize(false); imageView->setPosition(Vec2(widgetSize.width / 2.0f, widgetSize.height / 2.0f));