You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写绘制大量图形的方法?实现代码精简的技术问询

代码重构方案:精简绘图逻辑

第一步:提取重复颜色为常量

原代码反复解析相同颜色值,先把常用颜色定义成类级常量,避免重复计算:

private static final Color PERU = Color.decode("#CD853F");
private static final Color SANDY_BROWN = Color.decode("#F4A460");
private static final Color BLACK = Color.BLACK; // 直接用系统内置黑色常量

第二步:提取通用绘制方法

把「设置颜色+绘制图形」的重复逻辑抽成独立方法,减少冗余:

// 绘制带填充色的椭圆
private void drawFilledOval(Graphics gr, Color color, int x, int y, int width, int height) {
    gr.setColor(color);
    gr.fillOval(x, y, width, height);
}

// 绘制带填充色的多边形
private void drawFilledPolygon(Graphics gr, Color color, int[] xPoints, int[] yPoints, int pointCount) {
    gr.setColor(color);
    gr.fillPolygon(xPoints, yPoints, pointCount);
}

第三步:重构原绘图方法

用通用方法替代重复代码,逻辑更清晰简洁:

private void DrawEventPerformed(DrawEventArg evt) {
    Graphics gr = evt.getGraphics();

    drawFilledOval(gr, PERU, 300, 100, 200, 180);
    drawFilledOval(gr, SANDY_BROWN, 340, 180, 120, 80);
    drawFilledPolygon(gr, BLACK, new int[]{380, 400, 420}, new int[]{200, 230, 200}, 3);
    drawFilledOval(gr, BLACK, 340, 180, 20, 30);
    drawFilledOval(gr, BLACK, 440, 180, 20, 30);
    drawFilledOval(gr, PERU, 290, 80, 80, 80);
    drawFilledOval(gr, PERU, 273, 260, 250, 290);
    drawFilledOval(gr, SANDY_BROWN, 323, 350, 150, 180);
}

额外优化提示

  • 原代码里的Color.getColor("", Color.decode(...))完全多余,直接用Color.decode或系统常量更高效;
  • 如果这些图形是一个完整的形象(比如卡通角色),还可以进一步拆分出drawHead、drawBody这类语义化方法,让代码可读性更强。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 07:35:17