Cocos2d-x source code analysis: Control source code analysis (control components controlbutton)

Source: Internet
Author: User
Tags bitmask

Source code version from 3.1rc

Reprinted please note


Cocos2d-x source code analysis directory

Http://blog.csdn.net/u011225840/article/details/31743129


1. the overall design of the inherited structure control is quite beautiful. The parent class control defines the basis and management of the entire control event, although it inherits the layer, however, it is not associated with the implementation of the UI component. Implement different UI components in sub-classes (controlbutton, controlswitch, and controlstepper ). The following uses the source code to analyze control and controlbutton to discover the charm of object-oriented technology.
2. source code analysis 2.1 control should be familiar to my scheduler source code analysis friends. scheduler itself is a manager, and the specific scheduled action comes from callbackselector. This is also true in the overall design of control. control defines a series of situations to customize the event to be triggered, and whether the event triggers a certain invocation can be dynamically set. This invocation can be understood as a specific action.
2.1.1 eventtype
    enum class EventType    {        TOUCH_DOWN           = 1 << 0,    // A touch-down event in the control.        DRAG_INSIDE          = 1 << 1,    // An event where a finger is dragged inside the bounds of the control.        DRAG_OUTSIDE         = 1 << 2,    // An event where a finger is dragged just outside the bounds of the control.        DRAG_ENTER           = 1 << 3,    // An event where a finger is dragged into the bounds of the control.        DRAG_EXIT            = 1 << 4,    // An event where a finger is dragged from within a control to outside its bounds.        TOUCH_UP_INSIDE      = 1 << 5,    // A touch-up event in the control where the finger is inside the bounds of the control.        TOUCH_UP_OUTSIDE     = 1 << 6,    // A touch-up event in the control where the finger is outside the bounds of the control.        TOUCH_CANCEL         = 1 << 7,    // A system event canceling the current touches for the control.        VALUE_CHANGED        = 1 << 8      // A touch dragging or otherwise manipulating a control, causing it to emit a series of different values.    };

At the beginning, I don't understand such definition. But why do we need to set this? We can use the | operation to specify two Event Events at the same time. If we simply use 1 2 3 4, you cannot use | or other operations to uniquely identify multiple events. From top to bottom, the event is in the internal touch, internal drag, external drag, drag into, drag away, internal release, external release, cancel, the value changes.
2.1.2 state
    enum class State    {        NORMAL         = 1 << 0, // The normal, or default state of a control—that is, enabled but neither selected nor highlighted.        HIGH_LIGHTED   = 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.        DISABLED       = 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.        SELECTED       = 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.    };

Under the control component, each State has a corresponding UI format. In normal state, the view displayed by the UI can be different from the view displayed by the UI in the selected state. Access the state and UI through a map.
2.1.3 Manage events 2.1.3.1 sendactionsforcontrolevents !)
Void control: sendactionsforcontrolevents (eventtype controlevents) {// The role of retain and release is to ensure that the control will not be deleted during the execution of this actions. // Actions may release the event source ref -- control. Therefore, you must retain the event to ensure that all events are executed before release. Retain (); // For each control events for (INT I = 0; I <kcontroleventtotalnumber; I ++) {// If the given controlevents bitmask contains the curent event // bit adaptation if (INT) controlevents & (1 <I ))) {// call invocations const Auto & invocationlist = This-> dispatchlistforcontrolevent (Control: eventtype) (1 <I); For (const Auto & invocation: invocationlist) {invocation-> invoke (this) ;}} release ();}

Vector <invocation *> & Control: dispatchlistforcontrolevent (eventtype controlevent) {// This function is used to obtain the invocationvector vector <invocation *> * invocationlist = nullptr; auto iter = _ dispatchtable. find (INT) controlevent); // If the invocation list does not exist for the dispatch table, we create it if (iter = _ dispatchtable. end () {invocationlist = new vector <invocation *> (); _ dispatchtable [(INT) controlevent] = invocationlist;} else {invocationlist = ITER-> second ;} return * invocationlist ;}


2.1.3.2 addtargetwithactionforcontrolevents
void Control::addTargetWithActionForControlEvents(Ref* target, Handler action, EventType controlEvents){    // For each control events    for (int i = 0; i < kControlEventTotalNumber; i++)    {        // If the given controlEvents bitmask contains the curent event        if (((int)controlEvents & (1 << i)))        {            this->addTargetWithActionForControlEvent(target, action, (EventType)(1<<i));        }    }}
Void control: addtargetwithactionforcontrolevent (ref * target, Handler action, eventtype controlevent) {// create the invocation object invocation * invocation = invocation: Create (target, action, controlevent ); // Add the invocation into the dispatch list for the given control event Auto & eventinvocationlist = This-> dispatchlistforcontrolevent (controlevent); // at this time, pushback also retain eventinvocationlist. pushback (Invocation );}

2.1.3.3 removetargetwithactionforcontrolevent
void Control::removeTargetWithActionForControlEvents(Ref* target, Handler action, EventType controlEvents){     // For each control events    for (int i = 0; i < kControlEventTotalNumber; i++)    {        // If the given controlEvents bitmask contains the curent event        if (((int)controlEvents & (1 << i)))        {            this->removeTargetWithActionForControlEvent(target, action, (EventType)(1 << i));        }    }}


 
void Control::removeTargetWithActionForControlEvent(Ref* target, Handler action, EventType controlEvent){    // Retrieve all invocations for the given control event    //<Invocation*>    auto& eventInvocationList = this->dispatchListforControlEvent(controlEvent);        //remove all invocations if the target and action are null    //TODO: should the invocations be deleted, or just removed from the array? Won't that cause issues if you add a single invocation for multiple events?    if (!target && !action)    {        //remove objects        eventInvocationList.clear();    }     else    {        std::vector<Invocation*> tobeRemovedInvocations;                //normally we would use a predicate, but this won't work here. Have to do it manually        for(const auto &invocation : eventInvocationList) {            bool shouldBeRemoved=true;            if (target)            {                shouldBeRemoved=(target==invocation->getTarget());            }            if (action)            {                shouldBeRemoved=(shouldBeRemoved && (action==invocation->getAction()));            }            // Remove the corresponding invocation object            if (shouldBeRemoved)            {                tobeRemovedInvocations.push_back(invocation);            }        }        for(const auto &invocation : tobeRemovedInvocations) {            eventInvocationList.eraseObject(invocation);        }    }}


Before introducing controlbutton, I must re-emphasize the handling of the event type and status in the control source code: whether to use the bit to match can uniquely determine the storage and eliminate the impact of using the list, this method is suitable for scenarios where there are few Enum classes and multiple classes need to be passed at the same time.
2.2 controlbutton 2.2.1 touch determines when to trigger a controlbutton In the touch mechanism. It can be seen through analyzing its source code.
Bool controlbutton: ontouchbegan (touch * ptouch, event * pevent) {// whether to receive the touch if (! Istouchinside (ptouch) |! Isenabled () |! Isvisible () |! Hasvisibleparents () {return false;} // you can delete for (node * c = This-> _ parent; C! = Nullptr; C = C-> getparent () {If (c-> isvisible () = false) {return false ;}}_ ispushed = true; this-> sethighlighted (true); // The touch down event only triggers sendactionsforcontrolevents (Control: eventtype: touch_down) in began; return true ;}


Void controlbutton: ontouchmoved (touch * ptouch, event * pevent) {If (! Isenabled () |! Ispushed () | isselected () {If (ishighlighted () {sethighlighted (false);} return;} bool istouchmoveinside = istouchinside (ptouch ); // move inside and the current status is not highlight. It indicates that the event is moved from the external to the internal, and the drag enter if (istouchmoveinside &&! Ishighlighted () {sethighlighted (true); sendactionsforcontrolevents (Control: eventtype: drag_enter) ;}// inside move internally and when the current status is highlight, it indicates moving internally, trigger event drag inside else if (istouchmoveinside & ishighlighted () {sendactionsforcontrolevents (Control: eventtype: drag_inside);} // outside move but the current status is highlight, the event drag exit else if (! Istouchmoveinside & ishighlighted () {sethighlighted (false); sendactionsforcontrolevents (Control: eventtype: drag_exit);} // outside move and not highlight moves externally, trigger event drag outside else if (! Istouchmoveinside &&! Ishighlighted () {sendactionsforcontrolevents (Control: eventtype: drag_outside );}}

Void controlbutton: ontouchended (touch * ptouch, event * pevent) {_ ispushed = false; sethighlighted (false); // you should add a judgment here, when a controlbutton is placed on scrollview, tableview, or a layer that can be moved, // You should select a switch, determine whether the user needs to trigger the touch up inside and outside events based on the distance to move. If (istouchinside (ptouch) {sendactionsforcontrolevents (Control: eventtype: touch_up_inside);} else {sendactionsforcontrolevents (Control: eventtype: touch_up_outside );}}

void ControlButton::onTouchCancelled(Touch *pTouch, Event *pEvent){    _isPushed = false;    setHighlighted(false);    sendActionsForControlEvents(Control::EventType::TOUCH_CANCEL);}

2.2.2 create and needlayout control button is essentially a label and a scale9sprite. It can be seen in its initialization.
2.2.2.1 create problems
Bool controlbutton: initwithlabelandbackgroundsprite (node * node, scale9sprite * backgroundsprite) {If (Control: Init () {ccassert (node! = Nullptr, "label must not be nil."); labelprotocol * label = dynamic_cast <labelprotocol *> (node); ccassert (backgroundsprite! = Nullptr, "background sprite must not be nil."); ccassert (Label! = Nullptr | backgroundsprite! = Nullptr, ""); _ parentinited = true; _ ispushed = false; // adjust the background image by default setadjustbackgroundimage (true); setpreferredsize (size: zero ); // zooming button by default _ zoomontouchdown = true; _ scaleratio = 1.1f; // set the default anchor point ignoreanchorpointforposition (false); setanchorpoint (vec2: anchor_middle ); // set the nodes, label settitlelabel (node); setbackgroundsprite (backgroundsprite); // set the default color and opacity setcolor (color3b: White); setopacity (255.0f ); setopacitymodifyrgb (true); // initialize the dispatch table. The start state is normal settitleforstate (Label-> getstring (), control: State: normal ); settitlecolorforstate (node-> getcolor (), control: State: normal); settitlelabelforstate (node, control: State: normal); setbackgroundspriteforstate (backgroundsprite, control: state:: normal); setlabelanchorpoint (vec2: anchor_middle); // layout update needslayout (); Return true;} // couldn't init the control else {return false ;}}

Controlbutton stores state-related information with the view to be displayed on the UI through four maps. Titledispatch stores the string of the label in different states, titlecolor stores the color of the label in different States, and titlelabel stores the node bound to the title in different States, backgroundsprite is a Sprite in different States.
    std::unordered_map<int, std::string> _titleDispatchTable;    std::unordered_map<int, Color3B> _titleColorDispatchTable;    Map<int, Node*> _titleLabelDispatchTable;    Map<int, Scale9Sprite*> _backgroundSpriteDispatchTable;

The status is associated with these attributes through a series of get set functions.

2.2.2.2 needlayout
Void controlbutton: needslayout () {// overall step: Obtain the label and Sprite in a specific State, set the size of the button to the maximum value of the two, and then display the IF (! _ Parentinited) {return;} // hide the background and the label if (_ titlelabel! = Nullptr) {_ titlelabel-> setvisible (false);} If (_ backgroundsprite) {_ backgroundsprite-> setvisible (false );} // update anchor of all labels this-> setlabelanchorpoint (this-> _ labelanchorpoint); // update the label to match with the current State _ currenttitle = gettitleforstate (_ State ); _ currenttitlecolor = gettitlecolorforstate (_ state); this-> settitlelabel (gettitlelabelforstate (_ State); labelpro Tocol * label = dynamic_cast <labelprotocol *> (_ titlelabel); If (Label &&! _ Currenttitle. Empty () {label-> setstring (_ currenttitle);} If (_ titlelabel) {_ titlelabel-> setcolor (_ currenttitlecolor);} If (_ titlelabel! = Nullptr) {_ titlelabel-> setposition (vec2 (getcontentsize (). width/2, getcontentsize (). height/2);} // update the background sprite this-> setbackgroundsprite (this-> getbackgroundspriteforstate (_ State); If (_ backgroundsprite! = Nullptr) {_ backgroundsprite-> setposition (vec2 (getcontentsize (). width/2, getcontentsize (). height/2);} // get the title label size titlelabelsize; If (_ titlelabel! = Nullptr) {titlelabelsize = _ titlelabel-> getboundingbox (). size;} // adjust the background image if necessary if (_ doesadjustbackgroundimage) {// Add the margins if (_ backgroundsprite! = Nullptr) {_ backgroundsprite-> setcontentsize (SIZE (titlelabelsize. width + _ marginh * 2, titlelabelsize. height + _ marginv * 2);} else {// todo: shocould this also have margins if one of the preferred sizes is relaxed? If (_ backgroundsprite! = Nullptr) {size preferredsize = _ backgroundsprite-> getpreferredsize (); If (preferredsize. width <= 0) {preferredsize. width = titlelabelsize. width;} If (preferredsize. height <= 0) {preferredsize. height = titlelabelsize. height;} _ backgroundsprite-> setcontentsize (preferredsize);} // set the content size // in general, it is worth noting that here, assign the maximum size of the two to the rect recttitle; If (_ titlelabel! = Nullptr) {recttitle = _ titlelabel-> getboundingbox ();} rect rectbackground; If (_ backgroundsprite! = Nullptr) {rectbackground = _ backgroundsprite-> getboundingbox ();} rect maxrect = controlutils: rectunion (recttitle, rectbackground); setcontentsize (SIZE (maxrect. size. width, maxrect. size. height); If (_ titlelabel! = Nullptr) {_ titlelabel-> setposition (vec2 (getcontentsize (). width/2, getcontentsize (). height/2); // make visible the background and the label _ titlelabel-> setvisible (true);} If (_ backgroundsprite! = Nullptr) {_ backgroundsprite-> setposition (vec2 (getcontentsize (). width/2, getcontentsize (). height/2); _ backgroundsprite-> setvisible (true );}}

3. Summary other control components include: controlcolourpicker: color selector controlhuepicker: Tone selector controlswitch: Switch controlslider: slider controlstepper: Pedometer controlpotentiometer: Constant Current Meter... (A circular instrument that can be rotated and has a circular progress bar) controlsaturationbrightnesspicker: Saturation brightness Selector

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.