java canvas 画线_java – 在扩展Canvas时使用drawLine()绘制粗线

该博客演示了如何在Java中使用Graphics2D的setStroke方法结合BasicStroke类来绘制不同宽度的线条。通过设置不同的宽度、CAP_ROUND和JOIN_ROUND属性,展示了如何在Canvas上创建出粗细不一的线条效果。
摘要由CSDN通过智能技术生成

Graphics2D #setStroke控制绘制的线条样式.

BasicStroke是Stroke的默认实现,并且有许多参数,您最感兴趣的是宽度.

import java.awt.BasicStroke;

import java.awt.BorderLayout;

import java.awt.Dimension;

import java.awt.EventQueue;

import java.awt.Graphics;

import java.awt.Graphics2D;

import javax.swing.JFrame;

import javax.swing.JPanel;

import javax.swing.UIManager;

import javax.swing.UnsupportedLookAndFeelException;

public class TestStroke {

public static void main(String[] args) {

new TestStroke();

}

public TestStroke() {

EventQueue.invokeLater(new Runnable() {

@Override

public void run() {

try {

UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {

}

JFrame frame = new JFrame("Testing");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setLayout(new BorderLayout());

frame.add(new TestPane());

frame.pack();

frame.setLocationRelativeTo(null);

frame.setVisible(true);

}

});

}

public class TestPane extends JPanel {

@Override

public Dimension getPreferredSize() {

return new Dimension(200, 200);

}

@Override

protected void paintComponent(Graphics g) {

super.paintComponent(g);

Graphics2D g2d = (Graphics2D) g.create();

int width = getWidth();

int height = getHeight();

int xDif = width / 4;

int yDif = height / 4;

g2d.setStroke(new BasicStroke(1, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));

g2d.drawLine(xDif, yDif, width - xDif, yDif);

g2d.setStroke(new BasicStroke(2, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));

g2d.drawLine(width - xDif, yDif, width - xDif, height - yDif);

g2d.setStroke(new BasicStroke(3, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));

g2d.drawLine(width - xDif, height - yDif, xDif, height - yDif);

g2d.setStroke(new BasicStroke(4, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));

g2d.drawLine(xDif, height - yDif, xDif, yDif);

g2d.dispose();

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值