java basicstroke,动画与java.awt.BasicStroke中的虚线

Is there a way to produce animated dashed line using BasicStroke from java.awt? My desire is to have a running dashed-line in the same way that photoshop's rectangle marque tool has its line animated.

解决方案

Use a dashed line, a Thread (or a Swing Timer) & combine them with repaint() and some tweaking of where the dashes start and end - and there you have it.

Example

DnzXV.gif

package test;

import java.awt.BasicStroke;

import java.awt.Color;

import java.awt.Graphics2D;

import java.awt.Shape;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.awt.geom.Rectangle2D;

import java.awt.image.BufferedImage;

import java.io.File;

import java.io.IOException;

import javax.imageio.ImageIO;

import javax.swing.ImageIcon;

import javax.swing.JLabel;

import javax.swing.JOptionPane;

import javax.swing.SwingUtilities;

import javax.swing.Timer;

public class AnimatedStroke {

public static void main(String[] args) {

SwingUtilities.invokeLater(new Runnable() {

public void run() {

BasicStroke dashedStroke;

final int width = 100;

final int height = 30;

final BufferedImage image = new BufferedImage(

width,height,BufferedImage.TYPE_INT_ARGB);

final JLabel label = new JLabel(new ImageIcon(image));

int pad = 5;

final Shape rectangle = new Rectangle2D.Double(

(double)pad,(double)pad,

(double)(width-2*pad),

(double)(height-2*pad));

ActionListener listener = new ActionListener() {

float dashPhase = 0f;

float dash[] = {5.0f,5.0f};

@Override

public void actionPerformed(ActionEvent ae) {

dashPhase += 9.0f;

BasicStroke dashedStroke = new BasicStroke(

1.5f,

BasicStroke.CAP_ROUND,

BasicStroke.JOIN_MITER,

1.5f, //miter limit

dash,

dashPhase

);

Graphics2D g = image.createGraphics();

g.setColor(Color.WHITE);

g.fillRect(0,0,width,height);

g.setColor(Color.BLACK);

g.setStroke(dashedStroke);

g.draw(rectangle);

g.dispose();

label.repaint();

/*

if (dashPhase<100f) {

try {

ImageIO.write(

image,

"PNG",

new File("img" + dashPhase + ".png"));

} catch(IOException ioe) {

// we tried

}

}*/

}

};

Timer timer = new Timer(40, listener);

timer.start();

JOptionPane.showMessageDialog(null, label);

}

});

}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值