Cocos2d-x advanced UI controls

Source: Internet
Author: User

Corresponding to cccontrolextention on the official website. You can view the effect through ententiontest of testcpp.

Http://cocos2d-x.org/projects/cocos2d-x/wiki/CCControlExtension

The following content uses the extension library, so you need to add the library path and namespace

# Include "cocos-ext.h"
Using_ns_cc_ext;

Configure the extension path in the attribute and add the libextensions. Lib library.

Ccscale9sprite -- jiugongge Sprite

The tool for scaling images in the form of jiugongge works the same way as the 9patch of Android. It can make the buttons beautiful. However, click events cannot be processed.

Example:

Ccsize screensize = ccdirector: shareddirector ()-> getwinsize (); ccrect rect = ccrectmake (,); // read range from the original image, the parameters are coordinates x, y, and width, respectively, and the height is ccrect rect_inside = ccrectmake (,); // The variable part in the original image, that is, the part used for amplification. The parameters are interpreted as follows (X, Y, width, height ). Ccsize rect_9size = ccsizemake (screensize. width/2, screensize. height/2); ccscale9sprite * button = cocos2d: Extension: ccscale9sprite: Create ("button.png", rect, rect_inside); // button-> setcontentsize (ccsizemake (screensize. width, 57); button-> setpreferredsize (rect_9size); // the desired final button size. Button-> setposition (CCP (screensize. width/2, screensize. height/2.0f); addchild (button );

Note: ccscale9sprite: Create. If no rect is entered, the image is divided into nine parts according to the nine squares. The called Layer Code is as follows. If no rect is input, the default rect is ccrectzero. Check and define const ccrect ccrectzero = ccrectmake (,); that is, a rect of 0 size. You can refer to the example of cccontrolbutton, which directly calls create (char * file.

bool CCScale9Sprite::initWithFile(const char* file, CCRect rect,  CCRect capInsets){    CCAssert(file != NULL, "Invalid file for sprite");        CCSpriteBatchNode *batchnode = CCSpriteBatchNode::create(file, 9);    bool pReturn = this->initWithBatchNode(batchnode, rect, capInsets);    return pReturn;}
bool CCScale9Sprite::initWithBatchNode(CCSpriteBatchNode* batchnode, CCRect rect, bool rotated, CCRect capInsets){    if(batchnode)    {        this->updateWithBatchNode(batchnode, rect, rotated, capInsets);        this->setAnchorPoint(ccp(0.5f, 0.5f));    }    this->m_positionsAreDirty = true;        return true;}

This pair of button.png can be found in the cocos2d-x project, is a gradient chart. Magnified Effect

Cccontrolbutton -- unlike the ccscale9sprite, the button control can process events and must pass in ccscale9sprite as a parameter. The control event cccontrolevent can handle many action details. The definition in cccontrol. H is as follows:
/** Number of kinds of control event. */#define kControlEventTotalNumber 9/** Kinds of possible events for the control objects. */enum {    CCControlEventTouchDown           = 1 << 0,    // A touch-down event in the control.    CCControlEventTouchDragInside     = 1 << 1,    // An event where a finger is dragged inside the bounds of the control.    CCControlEventTouchDragOutside    = 1 << 2,    // An event where a finger is dragged just outside the bounds of the control.     CCControlEventTouchDragEnter      = 1 << 3,    // An event where a finger is dragged into the bounds of the control.    CCControlEventTouchDragExit       = 1 << 4,    // An event where a finger is dragged from within a control to outside its bounds.    CCControlEventTouchUpInside       = 1 << 5,    // A touch-up event in the control where the finger is inside the bounds of the control.     CCControlEventTouchUpOutside      = 1 << 6,    // A touch-up event in the control where the finger is outside the bounds of the control.    CCControlEventTouchCancel         = 1 << 7,    // A system event canceling the current touches for the control.    CCControlEventValueChanged        = 1 << 8      // A touch dragging or otherwise manipulating a control, causing it to emit a series of different values.};typedef unsigned int CCControlEvent;/** The possible state for a control.  */enum {    CCControlStateNormal       = 1 << 0, // The normal, or default state of a control—that is, enabled but neither selected nor highlighted.    CCControlStateHighlighted  = 1 << 1, // Highlighted state of a control. A control enters this state when a touch down, drag inside or drag enter is performed. You can retrieve and set this value through the highlighted property.    CCControlStateDisabled     = 1 << 2, // Disabled state of a control. This state indicates that the control is currently disabled. You can retrieve and set this value through the enabled property.    CCControlStateSelected     = 1 << 3  // Selected state of a control. This state indicates that the control is currently selected. You can retrieve and set this value through the selected property.};typedef unsigned int CCControlState;/** Number of kinds of control event. */#define kControlEventTotalNumber 9

Example: (remember to introduce the header file, naming control, and configure the cccontrol. h path when declaring the header file, because the cccontrolevent is used for declaration)

cocos2d::extension::CCScale9Sprite *backgroundButton = cocos2d::extension::CCScale9Sprite::create("button.png");cocos2d::extension::CCScale9Sprite *backgroundHighlightedButton = cocos2d::extension::CCScale9Sprite::create("buttonHighlighted.png");// Creates a button with this string as titleCCLabelTTF *titleButton = CCLabelTTF::create("hello", "Marker Felt", 30);    titleButton->setColor(ccc3(159, 168, 176));cocos2d::extension::CCControlButton *newbutton = cocos2d::extension::CCControlButton::create(titleButton, backgroundButton);newbutton->setBackgroundSpriteForState(backgroundHighlightedButton, cocos2d::extension::CCControlStateHighlighted);newbutton->setTitleColorForState(ccWHITE, cocos2d::extension::CCControlStateHighlighted);newbutton->setPosition(ccp (screenSize.width / 2, screenSize.height / 2));

Newbutton-> Reset (this, cccontrol_selector (helloworld: Touchdown), cccontroleventtouchdown); // note that the region is public, and addtargetwithactionforcontrolevent is protected. Do not miss S, otherwise, an error is reported: the endpoint Member/addtargetwithactionforcontrolevents cannot be accessed and the addtargetwithactionforcontrolevent addchild (newbutton) is called cyclically );

Refer to the following code

void CCControl::addTargetWithActionForControlEvents(CCObject* target, SEL_CCControlHandler action, CCControlEvent controlEvents){    // For each control events    for (int i = 0; i < kControlEventTotalNumber; i++)    {        // If the given controlEvents bitmask contains the curent event        if ((controlEvents & (1 << i)))        {            this->addTargetWithActionForControlEvent(target, action, 1<<i);                    }    }}

Cccontrolslider -- drag a bar cccontrolcolorpicker -- color selector cccontrolswitch -- switch control cccontrolpotentionmeter -- pressure gauge cccontrolstepper -- segment control ccscrollview -- scroll view cctabelview -- list view a list may not be seen by many cells, if only five cells are displayed, the entire table will generate only six cells. Then, when preparing to display a new cell, clear the invisible cell to the new cell. When we see the testcpp example, we will first find whether there are available cells. If not, a new one will be generated. If yes, we will use it cyclically. We only need to update the label, as shown in the following code.

Cctableviewcell * tableviewtestlayer: tablecellatindex (cctableview * Table, unsigned int idx) {ccstring * string = ccstring: createwithformat ("% d", idx ); cctableviewcell * cell = table-> dequeuecell (); If (! Cell) {Cell = new customtableviewcell (); cell-> autorelease (); ccsprite * sprite = ccsprite: Create ("images/icon.png "); sprite-> setanchorpoint (ccpointzero); sprite-> setposition (CCP (0, 0); cell-> addchild (sprite); cclabelttf * label = cclabelttf :: create (string-> getcstring (), "Helvetica", 20.0); label-> setposition (ccpointzero); label-> setanchorpoint (ccpointzero); label-> settag (123 ); // set tag cell-> addchild (Label);} else {maid * label = (cclabelttf *) cell-> getchildbytag (123 ); // obtain the initialized cell label according to the tag-> setstring (string-> getcstring ();} return cell ;}
 

To use tableview, remember to inherit the interface

Class tableviewtestlayer: Public cocos2d: cclayer, public cocos2d: Extension: cctableviewdatasource, public cocos2d: Extension: cctableviewdelegate

Initialization function of cctableviewdatasource

    static CCTableView* create(CCTableViewDataSource* dataSource, CCSize size, CCNode *container);

The following functions are inherited from the public cocos2d: Extension: cctableviewdatasource data source.

    virtual cocos2d::CCSize cellSizeForTable(cocos2d::extension::CCTableView *table);    virtual cocos2d::extension::CCTableViewCell* tableCellAtIndex(cocos2d::extension::CCTableView *table, unsigned int idx);    virtual unsigned int numberOfCellsInTableView(cocos2d::extension::CCTableView *table);

Cctableviewdelegate and inherit scrollview

Class cctableviewdelegate: Public ccscrollviewdelegate. To implement the following two interfaces (if there is no event processing, do not write the method)

    virtual void scrollViewDidScroll(cocos2d::extension::CCScrollView* view) {};    virtual void scrollViewDidZoom(cocos2d::extension::CCScrollView* view) {}

Cctableviewdelegate can call the following function to report the cell

void TableViewTestLayer::tableCellTouched(CCTableView* table, CCTableViewCell* cell){    CCLOG("cell touched at index: %i", cell->getIdx());}

When the click event ends, determine which cell is clicked (you can use this method to define other controls)

Void cctableview: cctouchended (cctouch * ptouch, ccevent * pevent) {If (! This-> isvisible () {return;} If (m_ptouches-> count () = 1 &&! This-> istouchmoved () {unsigned int index; cctableviewcell * cell; ccpoint point; point = This-> getcontainer ()-> converttouchtonodespace (ptouch ); if (m_evordering = kcctableviewfilltopdown) {ccsize cellsize = m_pdatasource-> cellsizefortable (this); point. y-= cellsize. height;} Index = This-> _ indexfromoffset (point); cell = This-> _ cellwithindex (INDEX); If (cell) {m_ptableviewdelegate-> tablecelltouched (this, cell ); // call tablecelltouched here} ccscrollview: cctouchended (ptouch, pevent );}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.