[LayaAir 2.0]分享一个Graphics画圆角矩形的封装

圆角矩形实践中用得频繁,做了一个封装分享出来,TS版本的,分2步:
 
1、在项目的libs目录中新建一个d.ts,写入画圆角矩形的函数声明
declare namespace laya.display {
    interface Graphics {
        /**
         * 绘制圆角矩形。
         * @param x   开始绘制的 X 轴位置。
         * @param y   开始绘制的 Y 轴位置。
         * @param width  矩形宽度。
         * @param height 矩形高度。
         * @param round     矩形圆角半径。
         * @param fillColor 填充颜色,或者填充绘图的渐变对象。
         * @param lineColor (可选)边框颜色,或者填充绘图的渐变对象。
         * @param lineWidth (可选)边框宽度。
         */
        drawRoundrect(x: number, y: number, width: number, height: number, round: number, fillColor: any, lineColor?: any, lineWidth?: number):void
    }
}
 
2、在Main.ts中写入实现
Laya.Graphics.prototype.drawRoundrect = function(x: number, y: number, width: number, height: number, round: number, fillColor: any, lineColor?: any, lineWidth?: number):void {
    if(this instanceof Laya.Graphics == false ){ return; }
    let sideMin:number = width<=height ? width : height;
    if(round<0){ round=0; }else if(round>sideMin/2){ round=sideMin/2; }
    this.drawPath(x, y, [
        ["moveTo", round, 0],
        ["lineTo", width-round, 0],
        ["arcTo", width, 0, width, round, round],
        ["lineTo", width, height-round],
        ["arcTo", width, height, width-round, height, round],
        ["lineTo", round, height],
        ["arcTo", 0, height, 0, height-round, round],
        ["lineTo", 0, round],
        ["arcTo", 0, 0, round, 0, round],
        ["closePath"]
    ],
    {
        fillStyle: fillColor
    }, lineWidth>0?{
        strokeStyle: lineColor,
        lineWidth: lineWidth,
        lineJoin: 'round',
        lineCap: 'round'
    }:null);
};
 
之后就可以使用了,如:mysprite.graphics.drawRoundrect(0, 0, 200, 100, 30, '#f00');
已邀请:

panda-星

赞同来自:

感谢分享,但是在使用的时候发现了一个问题,左下角绘制有错误
["moveTo", round, 0],
        ["lineTo", width-round, 0],
        ["arcTo", width, 0, width, round, round],
        ["lineTo", width, height-round],
        ["arcTo", width, height, width-round, height, round],
        ["lineTo", round, height],
        ["arcTo", 0, height, 0, height-round, round],
        ["lineTo", 0, round],  //这里要改成["lineTo", 0, height - round],
        ["arcTo", 0, 0, round, 0, round],
        ["closePath"]

要回复问题请先

商务合作
商务合作