cocos2dx与lua学习笔记之控件学习(一)

function BAGUI:showLabel()
    local ttfConfig = { }
    ttfConfig.fontFilePath = "simhei.ttf"
    ttfConfig.fontSize = 24
    ttfConfig.outlineSize = 0

    local nameLbl = cc.Label:create()
    nameLbl:setString("test label")
    nameLbl:setTTFConfig(ttfConfig)
    nameLbl:setColor(DisplayObjectUtil.convertHexToRGB("#f8f400"))
    nameLbl:setAnchorPoint(0, 0)
    nameLbl:setPosition(0, 0)
    view:addChild(nameLbl)
end

function BAGUI:showButton()
    local btn = ccui.Button:create()
    btn:loadTextureNormal("normal.png", ccui.TextureResType.plistType)
    btn:loadTexturePressed("pressed.png", ccui.TextureResType.plistType)
    btn:loadTextureDisabled("disabled.png", ccui.TextureResType.plistType)
    btn:setTitleFontName("simhei.ttf")
    btn:setTitleText("开始游戏")
    btn:setTitleColor(cc.c4b(255, 255, 255, 1))
    btn:setTitleFontSize(24)
    btn:setName("startBtn")
    btn:setTag(862)
    btn:setTouchEnabled(true)
    btn:setPosition(500, 400)
    btn:setScale(1.0, 1.0)
    btn:setAnchorPoint(cc.p(0.5, 0.5))
    btn:setContentSize(119.0, 50.0)
    view:addChild(btn)
    UIManager:widgetTouchExtent(btn, {
        callBack = function()
            UIManager:addUI(cc.Director:getInstance():getRunningScene(), Config_UI.CALLBOARDEDITOR.name)
        end
    } )
end

function BAGUI:showText()
    local text = ccui.Text:create()
    text:setFontName("simhei.ttf")
    text:setFontSize(24)
    text:setString("提示文本")
    text:setText("需要显示哦的文本内容")
    text:setPosition(300, 240)
    text:setAnchorPoint(cc.p(0.5, 0.5))
    text:setEnabled(true)
    text:setVisible(true)
    text:setRotation(0)
    text:setName("msgTxt")
    view:addChild(text)
end

function BAGUI:showImage()
    local img = ccui.ImageView:create("logo.png", ccui.TextureResType.plistType)
    img:setScale(2, 1)
    img:setAnchorPoint(cc.p(0.5, 0.5))
    img:setPosition(12, 12)
    img:setLocalZOrder(-1)
    img:setName("LOGO")
    img:setColor(cc.c4b(128, 128, 128, 1))
    img:setContentSize(100, 100)
    img:setTouchEnabled(true)
    img:setTag(2)
    view:addChild(img)
    img:addClickEventListener( function()
        print("image click")
    end )

    local img2 = ccui.ImageView:create()
    img2:loadTexture("img2.png", ccui.TextureResType.localType)
    view:addChild(img2)
end

function BAGUI:showScrollView()
    local scrollView = ccui.ScrollView:create()
    scrollView:setClippingEnabled(true)
    scrollView:setDirection(cc.SCROLLVIEW_DIRECTION_VERTICAL)
    scrollView:setBackGroundColorOpacity(102)
    scrollView:setBackGroundImageScale9Enabled(true)
    scrollView:setName("scrollView")
    scrollView:setTag(119)
    scrollView:setTouchEnabled(true)
    scrollView:setPosition(134, 90)
    scrollView:setAnchorPoint(cc.p(0.5, 0.5))
    scrollView:setColor(cc.c4b(255, 255, 255, 255))
    scrollView:setContentSize(cc.size(100, 100))
    -- 设置显示出来的区域大小“视口”
    scrollView:setInnerContainerSize(cc.size(400, 400))
    -- 设置内部容器的大小,决定了拖动的区域大小;它必须大于或等于setContentSize()。
    scrollView:setBoundEnabled(true)
    -- 是否开启拖动到头后的反弹效果
    scrollView:setLayoutType(ccui.LayoutType.VERTICAL)
    -- 垂直布局;ScrollView本身就是一种Layout

    --    scrollView:stopAutoScroll()
    --    scrollView:stopOverallScroll()
    --    scrollView:scrollToBottom()

    for i = 0, 10 do
        local btn = ccui.Button:create()
        btn:setName("btn" .. i)
        scrollView:addChild(btn)
    end

    local size1 = { }
    size1.width = 100
    size1.height = 500
    scrollView:setInnerContainerSize(size1)
    self.view:addChild(scrollView)

    scrollView:addEventListener( function(sender, type)
        if type == ccui.ScrollviewEventType.scrollToTop then
            print("scroll to top")
        elseif type == ccui.ScrollviewEventType.scrollToBottom then
            print("scroll to bottom")
        elseif type == ccui.ScrollviewEventType.scrollToLeft then
            print("scroll to left")
        elseif type == ccui.ScrollviewEventType.scrollToRight then
            print("scroll to right")
        else
            print("scroll to where ?")
        end
    end )
end


--[[
      1..子节点如果是RichText,或是文本信息。
         设置setVerticalSpace(),高度间隔。adjustToRealHeight(),自适应高度。
      2..设置子节点的锚点信息,否则高度不对称
  ]]
function BAGUI:showListView()
    local listView = ccui.ListView:create()
    listView:setDirection(cc.SCROLLVIEW_DIRECTION_VERTICAL)
    listView:setItemsMargin(0)
    listView:setAnchorPoint(cc.p(0.5, 0.5))
    listView:setContentSize(1000, 100)
    listView:setPosition(100, 100)
    listView:setBounceEnabled(true)
    listView:setInertiaScrollEnabled(true)
    -- 设置使用滚动惯性
    listView:setBackGroundImage("bg.png")
    listView:pushBackCustomItem("子节点")

    local layout = ccui.Layout:create()
    layout:setBackGroundColorType(ccui.LayoutBackGroundColorType.solid)
    layout:setBackGroundColor(color)
    layout:setContentSize(500, 50)
    layout:setAnchorPoint(cc.p(0.5, 0.5))

    local btn = ccui.Button:create("normal.png", "pressed.png")
    layout.addChild(btn)
    listView.addChild(layout)
    self.view.addChild(listView)
end

function BAGUI:showPageView()
    local director = cc.Director:getInstance()
    local pageView = ccui.PageView:create()
    pageView:setTouchEnabled(true)
    pageView:setContentSize(cc.size(500, 500))
    pageView:setPosition(cc.p((cc.winSize.width - 500) * 0.5,(cc.winSize.height - 500) * 0.5))
    for i = 0, 10 do
        local layout = ccui.Layout:create()
        local img = ccui.ImageView:create()
        layout.addChild(img)
        pageView.addWidgetToPage(layout, i, true)
    end

    pageView.scrollToPage(0)
    pageView:addEventListenerPageView( function(sennder, type)
        if tpye == ccui.PageViewEventType.turning then
            print(pageView.getCurPageIndex() + 1)
        end
    end )
end

function BAGUI:showCheckBox()
    local checkBox = ccui.CheckBox:create()
    checkBox:setTouchEnabled(true)
    chcckBox:setName("cb")
    checkBox:loadTextures("check_box_normal.png",
    "check_box_normal_press.png",
    "check_box_active.png",
    "check_box_normal_disable.png",
    "check_box_active_disable.png")
    checkBox:setPosition(cc.p(120, 300))
    -- 坐标
    checkBox:addEventListenerCheckBox(selectedHandler)
    -- 注册事件
    self.view:addChild(checkBox, 10)
    local function selectedHandler(sender, type)
        if tpye == ccui.CheckBoxEventType.selected then
            print("checkbox selected")
        elseif type == ccui.CheckBoxEventType.unselected then
            print("checkbox unselected")
        end
    end
end

function BAGUI:showRaidioButton()
    local radioBtnGroup = ccui.RadioButtonGroup:create()
    for i = 1, 10 do
        local radio = ccui.RadioButton:create("bg.png", "bgselected.png", ccui.TextureResType.localType)
        radio:setName("radio" .. i)
        radio:setTag(i * 10)
        radio:setZoomScale(0.05)
        radioBtnGroup:addRadioButton(radio)
    end
    radioBtnGroup:setAllowedNoSelection(true)
    radioBtnGroup:setPosition(cc.p(100, 100))
    radioBtnGroup:setTouchEnabled(true)
    self.view:addChild(radioBtnGroup)
    radioBtnGroup:setSelectedButton(1)
    radioBtnGroup:setSelectedButton(radioBtnGroup:getChildByName("radio1"))
    print(radioBtnGroup:getNumberOfRadioButtons())
    print(radioBtnGroup:getRadioButtonByIndex(1))
    print(radioBtnGroup:setSelectedButtonWithoutEvent(2))
    radioBtnGroup:addEventListener( function(sender, type)
        if type == ccui.CheckBoxEventType.selected then
            print("radio selected")
        else
            print("radio unselected")
        end
    end )
end

function BAGUI:showLoadingBar()
    local bar = ccui.LoadingBar:create("loading.png", ccui.TextureResType.localType, 0.5)
    bar:setName("loadingBar")
    bar:setTag(333)
    bar:setDirection(ccui.LoadingBarDirection.LEFT)
    bar:setPercent(0.3)
    bar:setPosition(cc.p(cc))
    bar:setScale9Enabled(true)
    bar:ignoreContentAdaptWithSize(true)
    bar:setContentSize(cc.size(500, 20))
    bar:getVirtualRendererSize()
    bar:getDescription()
    bar:setCapInsets(cc.rect(0, 0, 0, 0))
    bar:setTouchEnabled(true)
    self.view.addChild(bar)
    local interval = 1
    local ticker = -1
    local function startLoading()
        if bar.getPercent() ~= 1 then
            bar.setPercent(bar.getPercent() + 10)
        else
            bar.setPercent(1)
            scheduler.unscheduleGlobal(ticker)
            ticker = -1
        end
    end
    if ticker ~= -1 then
        scheduler.unscheduleGlobal(ticker)
        ticker = -1
    end
    ticker = scheduler.scheduleGlobal(startLoading, interval)
    ------------------------------------------------------------------

    local to1 = cc.ProgressTo:create(2, 100)
    local to2 = cc.ProgressTo:create(2, 100)

    local left1 = cc.ProgressTimer:create(cc.Sprite:create("dog.png"))
    left1:setType(cc.PROGRESS_TIMER_TYPE_RADIAL)
    left1:setPosition(cc.p(100, 10))
    left1:runAction(cc.RepeatForever:create(to1))
    left1:addTo(self)

    local right1 = cc.ProgressTimer:create(cc.Sprite:create("dog.png"))
    right1:setType(cc.PROGRESS_TIMER_TYPE_BAR)
    right1:setPosition(cc.p(400, 10))
    right1:runAction(cc.RepeatForever(to2))
    right1:addTo(self)

    -- self.barPro:setType(cc.PROGRESS_TIMER_TYPE_BAR)
    --[[
    setMidpoint:设置进度条的起点位置:cc.p(x, y)
    cc.p(0, 0)为左下角
    cc.p(1, 1)为右上角
    e.g.
    cc.p(0, y):x为0,不管y为0还是1,水平方向的起点为最左边,则进度条减少的方向为从右到左
    cc.p(x, 1):y为1,不管x为0还是1,垂直方向的起点为最上边,则进度条减少的方向为从下到上
    ]]
    -- self.barPro:setMidpoint(cc.p(0, 0))
    --[[
    setBarChangeRate:设置垂直和水平方向的进度:cc.p(x, y)
    x和y分别为水平方向和垂直方向,其值均为0或1,0表示该方向没有进度,1表示该方向有进度
    e.g.
    cc.p(1, 0)表示水平方向有进度,垂直方向无进度
    cc.p(1, 1)表示水平和垂直方向都有进度
    ]]
    -- self.barPro:setBarChangeRate(cc.p(1, 0))

    local to3 = cc.ProgressTo:create(2.5, 100)
    local to4 = cc.ProgressTo:create(2, 100)

    -- 创建进度条的动画渲染器
    local left = cc.ProgressTimer:create(cc.Sprite:create("dog.png"))
    -- 设置进度条类型,这里是条形进度类型
    left:setType(cc.PROGRESS_TIMER_TYPE_BAR)
    -- 设置圆心位置为左下角
    left:setMidpoint(cc.p(0, 0))
    -- 设置横向进度条变化率,y=0意味着没有竖向的变化
    left:setBarChangeRate(cc.p(1, 0))
    -- 设置在x=100,y为屏幕宽度一半的位置
    left:setPosition(cc.p(100, display.height / 2))
    -- 执行动作
    left:runAction(cc.RepeatForever:create(to3))
    -- 添加到层中
    left:addTo(self)

    -- 进度条渲染器,这是右边演示的进度条
    local right = cc.ProgressTimer:create(cc.Sprite:create("dog.png"))
    -- 设置渲染类型
    right:setType(cc.PROGRESS_TIMER_TYPE_BAR)
    -- Setup for a bar starting from the left since the midpoint is 1 for the x
    --  用来设定进度条横向前进的方向从左向右或是从右向左,这里是从右往左
    right:setMidpoint(cc.p(1, 0))
    -- Setup for a horizontal bar since the bar change rate is 0 for y meaning no vertical change
    -- 用来设置进度条增长按横向或是按纵向增长,这里是横向增长
    right:setBarChangeRate(cc.p(1, 0))
    -- 设置渲染器到右边
    right:setPosition(cc.p(display.width - 100, display.height / 2))
    -- 让它运行一个无限循环的进度动画,进度变化由控制器2来控制
    right:runAction(cc.RepeatForever:create(to4))
    right:addTo(self)
end

function BAGUI:showProgress()
    local barProBg = cc.Sprite:createWithSpriteFrameName("bar_progress_bg.png")
    local sprite = cc.Sprite:createWithSpriteFrameName("bar_pregress.png")
    self.barPro = cc.ProgressTimer:create(sprite)

    self.barPro:setType(cc.PROGRESS_TIMER_TYPE_BAR)

    self.barPro:setMidpoint(cc.p(0, 0))

    self.barPro:setBarChangeRate(cc.p(1, 0))
    local size = barProBg:getContentSize()
    self.barPro:setPosition(cc.p(size.width / 2, size.height / 2))
    barProBg:addChild(self.barPro)
    self.barPro:setPercentage(66)

    --------------------------------------------------------------

    local radialProBg = cc.Sprite:createWithSpriteFrameName("radial_progress_bg.png")
    -- 圆形进度条背景,若不需要可以省去
    local sprite = cc.Sprite:createWithSpriteFrameName("radial_pregress.png")
    self.radialPro = cc.ProgressTimer:create(sprite)
    -- 必须使用精灵创建进度条
    --[[
    setType:设置进度条类型
    cc.PROGRESS_TIMER_TYPE_RADIAL为圆形
    cc.PROGRESS_TIMER_TYPE_BAR为条形
    ]]
    self.radialPro:setType(cc.PROGRESS_TIMER_TYPE_RADIAL)
    --[[
    setReverseDirection:设置进度条的方向(只针对圆形进度条)
    true为顺时针
    false为逆时针
    ]]
    self.radialPro:setReverseDirection(true)
    local size = radialProBg:getContentSize()
    self.radialPro:setPosition(cc.p(size.width / 2, size.height / 2))
    radialProBg:addChild(self.radialPro)
    self.radialPro:setPercentage(66)
end

function BAGUI:showSlider()
    local slider = ccui.Slider:create()
    slider:loadBarTexture("bar.png", ccui.TextureResType.localType)
    slider:loadProgressBarTexture("progress.png", ccui.TextureResType.plistType)
    slider:loadSlidBallTextures("normal.png", "pressed.png", "disabled.png", ccui.TextureResType.localType)
    slider:setPercent(50)
    slider:setMaxPercent(100)
    slider:setName("slider")
    slider:setTouchEnabled(true)
    slider:setPosition(cc.p(100, 200))
    slider:addEventListener( function(sender, type)
        if type == ccui.SliderEventType.percentChanged then
            print("current percent is " .. slider:getPercent())
        end
    end )
    self.view:addChild(slider)
end

function BAGUI:showTextAtlas()
    -- digit_test.png内容为0123456789*=
    local textAtlas = ccui.TextAtlas:create("0", "ui/digit_test.png", 30, 48, "0")
    -- local textAtlas = ccui.TextAtlas:create("11:8;88", "ui/digit_test.png", 30, 48, "0")
    textAtlas:setAnchorPoint(0.5, 0.5)
    textAtlas:setPosition(cc.p(0, 0))
    self:addChild(textAtlas)
    textAtlas:setString("11:8;88")
    -- textAtlas的内容为:11*8=88
    -- 因为分割是通过ASCII码的控制字符的顺序进行偏移,
    -- 第十一个字符也就是控制字符“9”对应的ASCII码值(57)
    -- 的下一个ASCII码值(58)对应的控制字符也就是“:”,
    -- 所以“:”表示的就是图片资源上面的第十一个字符“*”,
    -- 同理“;”表示的就是图片字符上面的第十二个字符“=”。
end

function BAGUI:showRichText()
    local richText = ccui.RichText:create()
    richText:setContentSize(cc.size(100, 200))
    local r1 = ccui.RichElementText:create(1, cc.c3b(255, 196, 59), 255, "测试文本一", "simhei.ttf", 20)
    local r2 = ccui.RichElementText:create(2, cc.c3b(255, 126, 59), 255, "测试文本二", "simhei.ttf", 20)
    local r3 = ccui.RichElementImage:create(3, cc.c3b(128, 128, 0), 255, "richtext.png")
    ccs.armatureDataManager.addArmatureFileInfo("res/cocosui/100/100.ExportJson");
    local pAr = ccs.Armature.create("100");
    pAr.getAnimation().play("Animation1");
    local r4 = ccui.RichElementCustomNode:create(4, cc.c3b(128, 128, 0), 255, pAr)
    richText:pushBackElement(r1)
    richText:pushBackElement(r2)
    richText:pushBackElement(r3)
    richText:pushBackElement(r4)
    richText:setName("RICH_TEXT")
    richText:setPosition(cc.p(100, 100))
    self.view:addChild(richText)
end

function BAGUI:showTableView()
    local _tableview = cc.TableView:create(cc.size(size.width, size.height))
    _tableview:setDirection(cc.SCROLLVIEW_DIRECTION_VERTICAL)
    _tableview:setVerticalFillOrder(cc.TABLEVIEW_FILL_TOPDOWN)
    _tableview:setPosition(cc.p(0, 0))
    _tableview:setDelegate()
    self.view:addChild(_tableview)

    -- cell个数
    _tableview:registerScriptHandler( function(table_view)
        return self.cellNum
    end , cc.NUMBER_OF_CELLS_IN_TABLEVIEW)

    -- 每一行cell
    _tableview:registerScriptHandler( function(table_view, idx)
        return self:tableCellAtIndex(table_view, idx)
    end , cc.TABLECELL_SIZE_AT_INDEX)
    -- 每一行的宽高度
    _tableview:registerScriptHandler( function(table_view, idx)
        local _wid, _hei = self:cellSizeForTable(table_view, idx)
        return _wid, _hei
    end , cc.TABLECELL_SIZE_FOR_INDEX)

    _tableview:reloadData()
end

function BAGUI:showRelativeBox()
    local relativeBox = ccui.RelativeBox:create(cc.size(200, 200))
    local hbox = ccui.HBox:create(cc.size(500, 500))
    local vbox = ccui.VBox:create(cc.size(100, 100))
    self.view:addChild(hbox)
    hbox:addChild(relativeBox)
    hbox:addChild(vbox)
    local btn1 = ccui.Button:create()
    local btn2 = ccui.Button:create()
    hbox:addChild(btn1)
    relativeBox:addChild(btn2)
    btn2:setPosition(150, 150)
end

function BAGUI:showTextBMFont()
    local fntTxt = ccui.TextBMFont:create()
    fntTxt:setPosition(cc.p(0, 0))
    fntTxt:setFntFile("myFnt.fnt")
    fntTxt:setFntFile("myTTF.ttf")
    -- 两种都可以
    fntTxt:setText("提示文本")
    fntTxt:setString("显示一些文字内容")
    self.view:addChild(fntTxt)
end

function BAGUI:showTextField()
    local tf = ccui.TextField:create()
    tf:setFontName("simhei.ttf")
    tf:setFontSize(24)
    tf:setPosition(cc.p(0, 0))
    tf:addEventListener( function(sender, type)
        if type == ccui.TextFiledEventType.attach_with_ime then
            print("attach with ime")
        elseif type == ccui.TextFiledEventType.detach_with_ime then
            print("detach with ime")
        elseif type == ccui.TextFiledEventType.insert_text then
            print("insert text")
        elseif type == ccui.TextFiledEventType.delete_backward then
            print("delete backward")
        end
    end )
    self.view:addChild(tf)
end

function BAGUI:showVideoPlayer()
    local videoPlayer = ccexp.VideoPlayer:create()
    local pathMp4 = device.writablePath .. 'hotupdate//res//' .. mp4name
    if not io.exists(pathMp4) then
        pathMp4 = cc.FileUtils:getInstance():fullPathForFilename(mp4name)
        printCustom("got Mp4", pathMp4)
    end
    videoPlayer:setFileName(pathMp4)
    videoPlayer:setPosition(cc.p(display.width / 2, display.height / 2))
    videoPlayer:setAnchorPoint(cc.p(0.5, 0.5))
    videoPlayer:setContentSize(cc.size(display.width, display.height))
    -- 播放视频时是否始终保持高宽比
    videoPlayer:setKeepAspectRatioEnabled(false)
    videoPlayer:setFullScreenEnabled(true)
    videoPlayer:setVisible(true)

    self:addChild(videoPlayer, 99)

    videoPlayer:addEventListener( function(videoPlayer, eventType)
        if eventType == ccexp.VideoPlayerEvent.PLAYING then
            printCustom("LoginScene:playMp4 playing")
        elseif eventType == ccexp.VideoPlayerEvent.PAUSED then
            printCustom("LoginScene:playMp4 paused")
            if self.videoCouldSkip then
                videoPlayer:onPlayEvent(ccexp.VideoPlayerEvent.COMPLETED)
            end
        elseif eventType == ccexp.VideoPlayerEvent.STOPPED then
            printCustom("STOPPED")
        elseif eventType == ccexp.VideoPlayerEvent.COMPLETED then
            printCustom("LoginScene:playMp4 completed")
            videoPlayer:stop()
            self:performWithDelay( function(...)
                self:removeChild(videoPlayer)
                videoPlayer = nil
                if callback then
                    callback()
                end
            end , 0.01)
        end
    end )
    videoPlayer:play()
end

function BAGUI:showWebView()
    local webView = ccexp.WebView:create()
    webView:setContentSize(cc.size(1280, 720))
    webView:setAnchorPoint(cc.p(0, 0))
    webView:setPosition(cc.p(0, 0))
    webView:setScalesPageToFit(true)
    webView:loadHTMLString(true)
    webView:loadURL("http://www.sky.com")
    webView:setOnShouldStartLoading( function(sender, url)
        print("onWebView1ShouldStartLoading,url is ", url)
        return true
    end )
    webView:setOnDidFinishLoading( function(sender, url)
        print("onWebView1DidFinishLoading url is ", url)
    end )
    webView:setOnDidFailLoading( function(sender, url)
        print("onWebView1DidFailLoading url is ", url)
    end )
    webView:reload()
end

function BAGUI:ShowEditBox()
    local showText = ccui.Text:create()
    showText:setText("占位文本")
    showText:setPosition(cc.p(0,0))
    showText:setTouchEnabled(true)
    showText:setFontName("simhei.ttf")
    showText:setFontSize(24)

    local editBox = ccui.EditBox:create(self.editBox_bg:getContentSize(), "res/editbox_bg.png", ccui.TextureResType.plistType)
    editBox:setInputMode(cc.EDITBOX_INPUT_FLAG_PASSWORD)
    editBox:setInputFlag(cc.EDITBOX_INPUT_FLAG_INITIAL_CAPS_WORD)
    editBox:setReturnType(cc.KEYBOARD_RETURNTYPE_DONE)
    editBox:setAnchorPoint(cc.p(0, 1))
    editBox:setPosition(cc.p(0,0))
    editBox:setFontColor(cc.c3b(255, 255, 255))
    editBox:setVisible(false)
    editBox:registerScriptEditBoxHandler( function(eventType)
        if eventType == "return" or eventType == "ended" then
            local str = editBox:getText()
            if str ~= "" then
                showText:setString(str)
            end
        end
    end )
    self.view:addChild(self.editBox)
end

你可能感兴趣的:(cocos2dx)