2016-06-29 03:47

# java绘图时对多个图形（把这些图形视为一体）进行旋转操作

``````    @Override
public void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
//去锯齿
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

//清空原来的图形
g2d.setColor(Color.WHITE);
g2d.fillRect(0, 0, this.getWidth(), this.getHeight());
g2d.setColor(Color.BLACK);

//圆中心坐标
int xCenter = this.getWidth() / 2;
int yCenter = this.getHeight() / 2;
// 计算半径
int radius = (int) (Math.min(this.getWidth(), this.getHeight()) * 0.8*0.5);  //因为是半径，所以 1/2
// 画圆

//画时钟的12个数字(如果用rotate方法则数字会倾斜倒立)
for (int i = 0; i < 12; i++) {
//已知圆中心占坐标(x0,y0),半径r，角度a0,则圆上任一点坐标（x,y）计算：
//x = x0 + r * cos(ao * 3.14 /180)
//y = y0 + r * sin(ao * 3.14 /180)

double dd = Math.PI / 180 * i * (360 / 12); //每次转360/12度
int x = (xCenter - 4) + (int) ((radius - 12) * Math.cos(dd));
int y = (yCenter + 4) + (int) ((radius - 12) * Math.sin(dd));

//因为是从顺时钟3点钟开始画，所以索引i需要加上3
int j = i + 3; //这里可以改
if (j > 12) {
j = j - 12;
}
g2d.drawString(Integer.toString(j), x, y);
}

AffineTransform old = g2d.getTransform();

//时钟的60个刻度
for (int i = 0; i < 60; i++) {
int w = i % 5 == 0 ? 5 : 3;
g2d.fillRect(xCenter - 2, 28, w, 3);
g2d.rotate(Math.toRadians(6), xCenter, yCenter);  //每一小格转6度, 以圆心为中心点
}
//设置旋转重置
g2d.setTransform(old);

Calendar calendar = Calendar.getInstance();
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);

//画日期和星期
DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");  //datadormat是一个抽象类
DateFormat df2 = new SimpleDateFormat("E");  //星期的格式
g2d.drawRoundRect(xCenter - 30, yCenter + 30, 72, 35, 10, 10);
g2d.drawString(df1.format(calendar.getTime()), xCenter - 25, yCenter + 45);
g2d.drawString(df2.format(calendar.getTime()), xCenter - 12, yCenter + 60);

// 画时钟的图形
double hAngle = (hour - 12 + minute / 60d) * 360d / 12d;
int xhArr[] = {xCenter, xCenter + 9, xCenter, xCenter - 9};
int yhArr[] = {65, yCenter, yCenter + 10, yCenter};
g2d.drawPolygon(xhArr, yhArr, xhArr.length);
g2d.setTransform(old);

// 画分钟的图形
double mAngle = (minute + second / 60d) * 360d / 60d;
int xmArr[] = {xCenter, xCenter + 6, xCenter, xCenter - 6};
int ymArr[] = {45, yCenter, yCenter + 12, yCenter};
g2d.drawPolygon(xmArr, ymArr, xmArr.length);
g2d.setTransform(old);

// 画秒钟的图形
double sAngle = second * 360d / 60d;
g.drawLine(xCenter, yCenter + 10, xCenter, 35);
}
``````

• 点赞
• 写回答
• 关注问题
• 收藏
• 邀请回答

#### 2条回答默认 最新

• wang2046783134 2016-06-29 14:39
已采纳

没人回答，自己回答吧。。。。。

`````` graphics2D g2 = (graphics2D)g;
g2.translate(20, 50);
g2.scale(12, 50);
g2.rotate();
``````

graphics2D每次translate都会以当前的坐标系为基准：

`````` g.setColor(Color.black);
g.drawLine(10, 10, 20, 10);

g.translate(100, 100);

g.setColor(Color.yellow);
g.drawLine(10, 10, 20, 10);

g.translate(50, 50);

g.setColor(Color.red);
g.drawLine(10, 10, 20, 10);
``````

试一下就知道了
呜呜，没人解答，好像是这样吧。。。。。

点赞 打赏 评论
• wang2046783134 2016-06-29 04:02

补充一下，代码是网上的，我只是想修改成想的那样

点赞 打赏 评论