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 is working.
I have searched a bit and found a Java example, but Android doesn't have GeneralPath
or AffineTransform
.
Right now my code looks like the following (the arrowhead looks nothing like an arrowhead):
public class DrawableView extends View { Context mContext; private int centerX; private int centerY; private int radius; private double arrLength; private double arrHeading; private int margin = 10; public DrawableView(Context context) { super(context); mContext = context; } @Override protected void onDraw(Canvas canvas) { //Paint Background Paint background = new Paint(); background.setColor(getResources().getColor(R.color.background); canvas.drawRect(0, 0, getWidth(), getHeight(), background); //Set vars for Arrow Paint Paint paint = new Paint(); paint.setColor(getResources().getColor(R.color.arrowColor); centerX = getWidth() / 2; centerY = getHeight() / 2; arrLength = radius - 10; if(centerX < centerY) radius = centerX - margin; else radius = centerY - margin; //Draw Shaft int[] xy = findArrowPos(arrLength, arrHeading); canvas.drawLine(centerX, centerY, xy[0], xy[1], paint); //Draw ArrowHead //This is where I'm confused } private int[] findArrowPos(double length, double angle) { int[] points = new int[2]; double theta = Math.toRadians(angle); points[0] = centerX + (int) (length * Math.cos(theta)); points[1] = centerY + (int) (length * Math.sin(theta)); return points; } }
I have taken a look at the following threads for guidance:
* http://www.java-forums.org/awt-swing/6241-how-u-rotate-arrow-mark-line-moves-accordingly.html
* How to draw a directed arrow line in Java?
How about using "Path myPath = new Path();" where you would give the x and y positions to create a triangle using lines and filling it. You can read about it, here is an example I took from somewhere.
// create and draw triangles // use a Path object to store the 3 line segments // use .offset to draw in many locations // note: this triangle is not centered at 0,0 paint.setStyle(Paint.Style.STROKE); paint.setStrokeWidth(2); paint.setColor(Color.RED); Path path = new Path(); path.moveTo(0, -10); path.lineTo(5, 0); path.lineTo(-5, 0); path.close(); path.offset(10, 40); canvas.drawPath(path, paint); path.offset(50, 100); canvas.drawPath(path, paint); // offset is cumlative // next draw displaces 50,100 from previous path.offset(50, 100); canvas.drawPath(path, paint);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With