cocosLua 之 绘制随机线段

环境: cocos Lua 3.15 Xcode

注: 从个人博客园移植而来


示意图:
请添加图片描述

示例代码:(由于其Y轴坐标使用的是随机坐标,因此其运行代码,会导致每次效果不一)

-- 绘制折线图
local winSize = cc.Director:getInstance():getWinSize()
local DrawLineTest = class("DrawLineTest", function()
    return cc.Layer:create()
end)

function DrawLineTest:ctor()
    self:drawLineWnd()
end 

function DrawLineTest:drawLineWnd()
    math.randomseed(os.time())
    local drawNode = cc.DrawNode:create()
    self:addChild(drawNode,100)

    -- x,y轴阶段
    local startposX, startPosY = 200, 100           -- 原点坐标
    local xLen, yLen = 540, 300                     -- x,y轴长度
    local SPACEX, SPACEY = 60, 30                   -- x,y轴每段间隔
    local randlinepos = {}                          -- 随机点坐标
    for i = 1, 10 do 
        -- x轴坐标相关
        local labelX = ccui.Text:create(tostring((i-1)*100), "Arial", 18)
        labelX:setPosition(cc.p(startposX + (i - 1) * SPACEX, startPosY - 20))
        self:addChild(labelX)

        -- y轴坐标相关
        local labelY = ccui.Text:create(tostring((i-1)*100), "Arial", 18)
        labelY:setPosition(cc.p(startposX - 20, startPosY + (i -1) * SPACEY))
        self:addChild(labelY)

        -- y轴平行线相关
        local origin = cc.p(startposX, startPosY + (i - 1)* SPACEY)
        local destination = cc.p(startposX + xLen, startPosY + (i - 1)* SPACEY)
        local color = cc.c4f(0, 0, 1, 0.8)
        drawNode:drawLine(origin, destination,color)

        -- 绘制Y轴随机点,计算公式: x/len = 随机值/总数值
        local randPosY = math.floor(math.random(0,900) * yLen/900) + startPosY
        local pointSize = 5
        local color = cc.c4f(1,0,0,1)
        local newPos = cc.p(startposX + (i - 1) * SPACEX, randPosY)
        drawNode:drawPoint(newPos,pointSize, color)
        table.insert(randlinepos, newPos)
    end 

    -- 根据随机点连接线段
    local num = #randlinepos
    for i = 1, num do 
        if i >= 2 then 
            local origin = randlinepos[i-1]
            local destination = randlinepos[i]
            drawNode:drawLine(origin, destination, cc.c4f(1,1,0,1))
        end 
    end 
end

return DrawLineTest

DrawNode的使用相关,可参考:cocosLua 之 DrawNode

End

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

鹤九日

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值