How do I draw an arrowhead (in Android)?

后端 未结 8 512
一个人的身影
一个人的身影 2020-11-29 06:29

I\'m fairly new to Android and have been toying around with Canvas. I\'m attempting to draw an arrow but I\'m only having luck with drawing the shaft, none of the arrowhead

8条回答
  •  萌比男神i
    2020-11-29 07:15

    If you are looking for the solution to draw thousands of arrows under a second, with fixed length head lines, try this function (draws only arrow heads):

    private void fillArrow(Paint paint, Canvas canvas, float x0, float y0, float x1, float y1) {
        paint.setStyle(Paint.Style.STROKE);
    
        int arrowHeadLenght = 10;
        int arrowHeadAngle = 45;
        float[] linePts = new float[] {x1 - arrowHeadLenght, y1, x1, y1};
        float[] linePts2 = new float[] {x1, y1, x1, y1 + arrowHeadLenght};
        Matrix rotateMat = new Matrix();
    
        //get the center of the line
        float centerX = x1;
        float centerY = y1;
    
        //set the angle
        double angle = Math.atan2(y1 - y0, x1 - x0) * 180 / Math.PI + arrowHeadAngle;
    
        //rotate the matrix around the center
        rotateMat.setRotate((float) angle, centerX, centerY);
        rotateMat.mapPoints(linePts);
        rotateMat.mapPoints(linePts2);
    
        canvas.drawLine(linePts [0], linePts [1], linePts [2], linePts [3], paint);
        canvas.drawLine(linePts2 [0], linePts2 [1], linePts2 [2], linePts2 [3], paint);
    }
    

    Based on https://gamedev.stackexchange.com/questions/44456/drawing-lines-on-android-with-matrix

提交回复
热议问题