You need to enable JavaScript to run this app. 如何用几何公式在ScriptUI中绘制带半圆侧边的自定义按钮
优惠活动
大模型
产品
解决方案
定价
更多

如何用几何公式在ScriptUI中绘制带半圆侧边的自定义按钮

用几何计算实现ScriptUI对话框的Adobe风格圆角按钮

要实现类似Adobe官方样式的两侧半圆圆角按钮,核心是利用圆的几何特性绘制圆弧,结合直线拼接成完整的胶囊形路径。半圆的半径等于按钮高度的一半,这样两侧圆弧能和上下直线完美衔接,避免直线模拟的生硬感。

初始代码(直线模拟圆角)

最初用多段直线拼接模拟圆角,过渡效果生硬:

var dlg = new Window("dialog", "圆角按钮示例");
var btn = dlg.add("button", [10,10,150,50], "点击我");

btn.onDraw = function(g) {
    var bounds = this.bounds;
    // 用直线分段模拟圆角(过渡生硬)
    g.moveTo(bounds.x + 20, bounds.y);
    g.lineTo(bounds.x + bounds.width - 20, bounds.y);
    g.lineTo(bounds.x + bounds.width, bounds.y + 20);
    g.lineTo(bounds.x + bounds.width, bounds.y + bounds.height - 20);
    g.lineTo(bounds.x + bounds.width - 20, bounds.y + bounds.height);
    g.lineTo(bounds.x + 20, bounds.y + bounds.height);
    g.lineTo(bounds.x, bounds.y + bounds.height - 20);
    g.lineTo(bounds.x, bounds.y + 20);
    g.closePath();
    g.fillPath();
    // 绘制文字
    g.drawString(this.text, bounds.x + 40, bounds.y + 15);
};

dlg.show();

改进后代码(几何计算绘制半圆)

通过圆的参数方程和圆弧绘制方法,实现流畅的两侧半圆:

var dlg = new Window("dialog", "Adobe风格圆角按钮");
var btn = dlg.add("button", [10,10,150,50], "点击我");

btn.onDraw = function(g) {
    var bounds = this.bounds;
    var r = bounds.height / 2; // 半圆半径等于按钮高度的一半
    var centerLeft = [bounds.x + r, bounds.y + r]; // 左侧半圆的圆心
    var centerRight = [bounds.x + bounds.width - r, bounds.y + r]; // 右侧半圆的圆心

    // 开始绘制路径
    g.moveTo(centerLeft[0], bounds.y); // 移动到左侧半圆顶端

    // 绘制顶部直线
    g.lineTo(centerRight[0], bounds.y);

    // 绘制右侧上半圆到右下角
    g.arc(centerRight[0], centerRight[1], r, 0, Math.PI);

    // 绘制底部直线
    g.lineTo(centerLeft[0], bounds.y + bounds.height);

    // 绘制左侧下半圆回到起点
    g.arc(centerLeft[0], centerLeft[1], r, Math.PI, 2 * Math.PI);

    // 填充按钮底色
    g.fillColor = new SolidColor(0x33, 0x99, 0xff);
    g.fillPath();

    // 居中绘制白色文字
    g.textColor = new SolidColor(0xff, 0xff, 0xff);
    var textWidth = g.measureString(this.text).width;
    var textX = bounds.x + (bounds.width - textWidth)/2;
    var textY = bounds.y + (bounds.height - 16)/2;
    g.drawString(this.text, textX, textY);
};

dlg.show();

关键几何逻辑说明

  • 半圆半径r取按钮高度的一半,确保圆弧与按钮上下边缘完全贴合
  • 左侧半圆的圆心位于按钮左边缘向内偏移r的位置,垂直居中;右侧半圆圆心同理
  • 使用arc()方法绘制半圆,通过起始角度(0到π为右侧下半圆,π到2π为左侧上半圆)控制圆弧方向
  • 路径闭合后填充底色,再居中绘制文字,还原Adobe风格按钮的视觉效果

内容的提问来源于stack exchange,提问作者user18714172

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 15:00:59