---
title: "awt画带箭头的函数"
author: "星海孤舟"
date: "2011-04-28T14:59:00Z"
tags: []
categories: ["编程语言"]
slug: "awt"
draft: false
lastmod: "2011-04-28T14:59:00Z"
id: 1021620
url: "https://keith3321.iteye.com/blog/1021620"
---

public void drawAL(int sx, int sy, int ex, int ey, Graphics2D g2)  
    {  
        g2.setStroke(new BasicStroke(1.5f)) ;  
        double H = 8; // 箭头高度    
        double L = 3.5; // 底边的一半    
        int x3 = 0;  
        int y3 = 0;  
        int x4 = 0;  
        int y4 = 0;  
        double awrad = Math.atan(L / H); // 箭头角度    
        double arraow\_len = Math.sqrt(L * L + H * H); // 箭头的长度    
        double\[] arrXY\_1 = rotateVec(ex - sx, ey - sy, awrad, true, arraow\_len);  
        double\[] arrXY\_2 = rotateVec(ex - sx, ey - sy, -awrad, true, arraow\_len);  
        double x\_3 = ex - arrXY\_1\[0]; // (x3,y3)是第一端点    
        double y\_3 = ey - arrXY\_1\[1];  
        double x\_4 = ex - arrXY\_2\[0]; // (x4,y4)是第二端点    
        double y\_4 = ey - arrXY\_2\[1];

        Double X3 = new Double(x\_3);  
        x3 = X3.intValue();  
        Double Y3 = new Double(y\_3);  
        y3 = Y3.intValue();  
        Double X4 = new Double(x\_4);  
        x4 = X4.intValue();  
        Double Y4 = new Double(y\_4);  
        y4 = Y4.intValue();  
        // 画线    
        g2.drawLine(sx, sy, ex, ey);  
        GeneralPath triangle = new GeneralPath();  
        triangle.moveTo(ex, ey);  
        triangle.lineTo(x3, y3);   
        triangle.lineTo(x4, y4);  
        triangle.closePath();  
        //实心箭头    
        g2.fill(triangle);  
        //非实心箭头    
        //g2.draw(triangle);  

    }

    // 计算    
    public double\[] rotateVec(int px, int py, double ang, boolean isChLen, double newLen)  
    {

        double mathstr\[] = new double\[2];  
        // 矢量旋转函数，参数含义分别是x分量、y分量、旋转角、是否改变长度、新长度    
        double vx = px * Math.cos(ang) - py * Math.sin(ang);  
        double vy = px * Math.sin(ang) + py * Math.cos(ang);  
        if (isChLen) {  
            double d = Math.sqrt(vx * vx + vy * vy);  
            vx = vx / d * newLen;  
            vy = vy / d * newLen;  
            mathstr\[0] = vx;  
            mathstr\[1] = vy;  
        }  
        return mathstr;  
    }