Drawing on canvas with paint in better resolution? (Android) - java

I made a little loading circle with Canvas and Paint.
This is my first attempt to use these classes so it could be something I used wrong.
My problem is, that the resolution of painting are too low. I can clearly see the pixels.
How could I improve on this?
By the way this is my class:
public class LoadingCircle extends LinearLayout {
public LoadingCircle(Context context, AttributeSet attrs) {
super(context, attrs);
setWillNotDraw(false);
}
// time
int countDownTime = 180;
Paint paint = new Paint();
RectF oval = new RectF();
Path path = new Path();
// value
int value = 360 / countDownTime;
// starting progress
int progress = -360 - value;
#Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
float width = (float) getWidth();
float height = (float) getHeight();
float center_x = width / 2, center_y = height / 2;
float loadingRadius = (float) ((width / 2)*0.85);
float whiteRadius = (float) (loadingRadius * 1.06);
float greenRadius = (float) (loadingRadius * 1.14);
// **background green circle**/
oval.set(center_x - greenRadius, center_y - greenRadius, center_x + greenRadius, center_y + greenRadius);
paint.setColor(Color.parseColor("#a3d47b"));
paint.setStyle(Paint.Style.FILL_AND_STROKE);
canvas.drawArc(oval, 270, 360, true, paint);
// ****//
// **background green circle**/
oval.set(center_x - whiteRadius, center_y - whiteRadius, center_x + whiteRadius, center_y + whiteRadius);
paint.setColor(Color.parseColor("#ffffff"));
paint.setStyle(Paint.Style.FILL_AND_STROKE);
canvas.drawArc(oval, 270, 360, true, paint);
// **Loading circle**//
path.addCircle(center_x, center_y, loadingRadius, Path.Direction.CW);
paint.setColor(Color.parseColor("#71b23c"));
paint.setStyle(Paint.Style.FILL_AND_STROKE);
oval.set(center_x - loadingRadius, center_y - loadingRadius, center_x + loadingRadius, center_y + loadingRadius);
progress = progress + value;
Log.i("proges: ", progress + "");
canvas.drawArc(oval, 270, progress, true, paint);
// /**//
}
public void setCountDownTime(int time) {
this.countDownTime = time;
this.value = 360 / countDownTime;
this.progress = -360 - value;
}
// reseting loading circle
public void reset() {
this.progress = -360 - value;
this.invalidate();
}
}

Declare paint like this:
final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
This will enable the antialiasing and you'll get rid of that ugly pixellation.
Or, you can do it in your function:
paint.setAntiAlias(true);

Related

java android path animation

So I am nearly at the end.
I have been researching the whole day on how to do this.
Draw a path which grows(animation) from one point to another.
I have tried it with Matrix, but that just ended with turning my whole paths.
Here is a image of my project:
my project
My goal is to draw a animated path from one circle to the other.
Code:
public void init(#Nullable AttributeSet attr) {
circle = new Paint();
circle.setColor(Color.GREEN);
circle.setStyle(Paint.Style.FILL);
circle.setAntiAlias(true);
line = new Paint();
line.setColor(Color.GREEN);
line.setStyle(Paint.Style.STROKE);
line.setStrokeWidth(10);
line.setAntiAlias(true);
Collections.addAll(height, 100, 20, 50, 40, 70, 10, 50); // in percent
System.out.println(height.size() + " this is the size");
}
#Override
protected void onDraw(Canvas canvas) {
float y = getHeight() / 20 * 14;
float x = getWidth() / 8;
float radius = (canvas.getWidth() * canvas.getHeight()) / 40940;
for (int c = 1; c < 8; c++) {
System.out.println("at " + c);
canvas.drawCircle(x * c, y - ((getHeight() / 20) * (height.get(c - 1) / 10)), radius, circle);
points.add(new PointF(x * c, (y - ((getHeight() / 20) * (height.get(c - 1) / 10)))));
}
}
Please Help,
Thanks
you just need animate the path using ValueAnimator
create one path object
Path path = new Path();
and create animator
ValueAnimator animator = new ValueAnimator();
float startX = // starting circle x co-ordinate
float startY = // starting circle y co-ordinate
float endX = // end circle x co-ordinate
float endY = // end circle y co-ordinate
PropertyValuesHolder propertyX = PropertyValuesHolder.ofFloat("x",startX,endX);
PropertyValuesHolder propertyY = PropertyValuesHolder.ofFloat("y",startY,endY);
valueAnimator.setValues(propertyX,propertyY);
valueAnimator.setDuration(1000); // animation time
valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animation) {
float x = (float) animation.getAnimatedValue("x");
float y = (float) animation.getAnimatedValue("y");
path.lineTo(x,y);
invalidate();
}
});
valueAnimator.start();
and in onDraw() draw the path
canvas.drawPath(path,paint);

Trying to draw custom view How to Detect which slice is clicked

I am creating custom view, which is like screen below. I can draw views but I am unable to create separate click events for each view. How to set separate click events for each arc view?. Thanks in advance.
Here is the code:
ArcView.java
public class ItemView extends View {
Utils utils;
int left, right, top, bottom;
private int color;
private int start;
private int sweep;
private boolean inner;
private RectF oval;
public float center_x, center_y;
int divOn;
public float radius;
public ItemView(Context context, int color, int start, int sweep) {
super(context);
this.color = color;
this.start = start;
this.sweep = sweep;
utils = Utils.getInstance(getContext());
}
public ItemView(Context context, int color, int start, int sweep, boolean inner, int divOn) {
super(context);
this.color = color;
this.start = start;
this.sweep = sweep;
this.inner = inner;
this.divOn = divOn;
utils = Utils.getInstance(getContext());
}
public RectF getOval() {
return oval;
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//There is another flag for inner white circle
if (inner) {
float width = (float) getWidth();
float height = utils.getScreenHeight() - utils.getActionBarSize();
radius = (width - utils.dpTopixel(50)) / divOn;
Path path = new Path();
path.addCircle((width - utils.dpTopixel(50)) / divOn,
(height - utils.dpTopixel(50)) / divOn, radius,
Path.Direction.CW);
Paint paint = new Paint();
paint.setColor(ContextCompat.getColor(getContext(), color));
paint.setStrokeWidth(5);
paint.setStyle(Paint.Style.FILL);
paint.setAntiAlias(true);
final RectF oval = new RectF();
paint.setStyle(Paint.Style.FILL);
left = -(int) radius;
right = (int) radius;
top = (getHeight() / 2) - (int) radius;
bottom = (getHeight() / 2) + (int) radius;
oval.set(left,
top,
right,
bottom);
canvas.drawArc(oval, start, sweep, true, paint);
} else {
float width = (float) getWidth();
float height = utils.getScreenHeight() - utils.getActionBarSize();
float radius;
radius = (width - utils.dpTopixel(50)) / divOn;
Path path = new Path();
path.addCircle((width - utils.dpTopixel(50)) / 1,
(width - utils.dpTopixel(50)) / 1, radius,
Path.Direction.CW);
Paint paint = new Paint();
paint.setColor(ContextCompat.getColor(getContext(), color));
paint.setStrokeWidth(5);
paint.setStyle(Paint.Style.FILL);
paint.setAntiAlias(true);
oval = new RectF();
paint.setStyle(Paint.Style.FILL);
TextPaint textPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG | Paint.SUBPIXEL_TEXT_FLAG);
textPaint.setColor(ContextCompat.getColor(getContext(), R.color.white));
textPaint.setTextAlign(Paint.Align.CENTER);
/*Paint.FontMetrics metrics = paint.getFontMetrics();
float textheight = Math.abs(metrics.top - metrics.bottom);
float x = getWidth() / 2;
float y = (getHeight() / 2) + (height / 2);
canvas.drawText("My Text", x, y, paint);*/
left = -(int) radius;
right = (int) radius;
top = (getHeight() / 2) - (int) radius;
bottom = (getHeight() / 2) + (int) radius;
center_x = width / 2;
center_y = utils.getOffset();
int xPos = (getWidth() / 2);
int yPos = (int) ((getHeight() / 2) - ((textPaint.descent() + textPaint.ascent()) / 2)) ;
//((textPaint.descent() + textPaint.ascent()) / 2) is the distance from the baseline to the center.
oval.set(left,
top,
right,
bottom);
canvas.drawArc(oval, start, sweep, true, paint);
}
}
}
utils class to detect height and width and convert to px
i want equation to check i click which circle
Create a slice selected listener, override the onTouchEvent in your custom class, calculate which slice the touch event (with the action ACTION_UP) is on using the x,y values. You can then call the function from your slice selected listener and pass details about the selected slice.

Get the width of a the secondaryProgress within a Android ProgressBar

I have a progress bar with text in which I have overridden the onDraw like so:
#Override
protected synchronized void onDraw(Canvas canvas) {
super.onDraw(canvas);
Paint textPaint = new Paint();
textPaint.setAntiAlias(true);
textPaint.setColor(textColor);
textPaint.setTextSize(textSize);
Rect bounds = new Rect();
textPaint.getTextBounds(text, 0, text.length(), bounds);
float fx = getX();
float fy = getY();
int x = getWidth() / 2 - bounds.centerX();
int y = getHeight() / 2 - bounds.centerY();
canvas.drawText(text, x, y, textPaint);
}
I am trying to position the text inside of the secondary progress but not really sure how get the the current width of the secondary progress, basically the width of the current progress.
For now I just used a work around, basically I get the percentage of the progress and then multiply it by the density. I needed to align the text 20dp within the progress bar:
#Override
protected synchronized void onDraw(Canvas canvas) {
super.onDraw(canvas);
Paint textPaint = new Paint();
textPaint.setAntiAlias(true);
textPaint.setColor(textColor);
textPaint.setTextSize(textSize);
Rect bounds = new Rect();
textPaint.getTextBounds(text, 0, text.length(), bounds);
float density = getContext().getResources().getDisplayMetrics().density;
float percentage = getProgress() / 100.0f;
float x = getWidth() * percentage - (20 * density);
float y = getHeight() / 2 - bounds.centerY();
canvas.drawText(text, x, y, textPaint);
}

Dynamically draw arc

I draw an arc using onDraw(canvas):
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new MyView(this));
}
public class MyView extends View {
public MyView(Context context) {
super(context);
}
#Override
public void onDraw(Сanvas canvas) {
super.onDraw(canvas);
float width = (float) getWidth();
float height = (float) getHeight();
float radius;
if (width > height) {
radius = height / 4;
} else {
radius = width / 4;
}
final Paint paint = new Paint();
paint.setColor(Color.WHITE);
paint.setStrokeWidth(50);
paint.setStyle(Paint.Style.STROKE);
float center_x, center_y;
center_x = width / 2;
center_y = height / 4;
final RectF oval = new RectF();
oval.set(center_x - radius, center_y - radius, center_x + radius,
center_y + radius);
paint.setStyle(Paint.Style.STROKE);
center_x = width / 2;
center_y = height * 3 / 4;
oval.set(center_x - radius, center_y - radius, center_x + radius,
center_y + radius);
canvas.drawArc(oval, -90, 45, false, paint);
}
}
Tell me, how to dynamically change the value of sweepAngle() == 45 in line
canvas.drawArc(oval, -90, 45, false, paint)?
One solution would be to have a sweepAngle field in your class, and use that instead of 45 in drawing the arc. Then have a timer that periodically adds to sweepAngle and redraws the canvas.

How do I draw an arrowhead (in Android)?

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);
My Arrow Drawing code, maybe it can be of some use for somebody:
/**
* Draw an arrow
* change internal radius and angle to change appearance
* - angle : angle in degrees of the arrows legs
* - radius : length of the arrows legs
* #author Steven Roelants 2017
*
* #param paint
* #param canvas
* #param from_x
* #param from_y
* #param to_x
* #param to_y
*/
private void drawArrow(Paint paint, Canvas canvas, float from_x, float from_y, float to_x, float to_y)
{
float angle,anglerad, radius, lineangle;
//values to change for other appearance *CHANGE THESE FOR OTHER SIZE ARROWHEADS*
radius=10;
angle=15;
//some angle calculations
anglerad= (float) (PI*angle/180.0f);
lineangle= (float) (atan2(to_y-from_y,to_x-from_x));
//tha line
canvas.drawLine(from_x,from_y,to_x,to_y,paint);
//tha triangle
Path path = new Path();
path.setFillType(Path.FillType.EVEN_ODD);
path.moveTo(to_x, to_y);
path.lineTo((float)(to_x-radius*cos(lineangle - (anglerad / 2.0))),
(float)(to_y-radius*sin(lineangle - (anglerad / 2.0))));
path.lineTo((float)(to_x-radius*cos(lineangle + (anglerad / 2.0))),
(float)(to_y-radius*sin(lineangle + (anglerad / 2.0))));
path.close();
canvas.drawPath(path, paint);
}
I try this code it has been working perfectly:
switch (event.getAction())
{
case MotionEvent.ACTION_DOWN:
mPath.reset();
mPath.moveTo(x, y);
mX = x;
mY = y;
startPoint = new PointF(event.getX(), event.getY());
endPoint = new PointF();
invalidate();
break;
case MotionEvent.ACTION_MOVE:
float dx = Math.abs(x - mX);
System.out.println("action move");
float dy = Math.abs(y - mY);
if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE)
{
// currentDrawingPath.path.quadTo(mX,mY,(x + mX)/2, (y + mY)/2);
}
mX = x;
mY = y;
endPoint.x = event.getX();
endPoint.y = event.getY();
isDrawing = true;
invalidate();
break;
case MotionEvent.ACTION_UP:
mPath.lineTo(mX, mY);
float deltaX = endPoint.x-startPoint.x;
float deltaY = endPoint.y-startPoint.y;
float frac = (float) 0.1;
float point_x_1 = startPoint.x + (float) ((1 - frac) * deltaX + frac * deltaY);
float point_y_1 = startPoint.y + (float) ((1 - frac) * deltaY - frac * deltaX);
float point_x_2 = endPoint.x;
float point_y_2 = endPoint.y;
float point_x_3 = startPoint.x + (float) ((1 - frac) * deltaX - frac * deltaY);
float point_y_3 = startPoint.y + (float) ((1 - frac) * deltaY + frac * deltaX);
mPath.moveTo(point_x_1, point_y_1);
mPath.lineTo(point_x_2, point_y_2);
mPath.lineTo(point_x_3, point_y_3);
mPath.lineTo(point_x_1, point_y_1);
mPath.lineTo(point_x_1, point_y_1);
mCanvas.drawPath(mPath, ppaint);
endPoint.x = event.getX();
endPoint.y = event.getY();
isDrawing = false;
invalidate();
break;
default:
break;
}
I've been having the same problem, I need an arrow to point in a certain direction. After playing around with drawing algorithms I decided the simplest method is to use a bitmap & simply use a Matrix to rotate it, e.g.
ImageView image = (ImageView) findViewById(R.id.bitmap_image);
Bitmap bMap = BitmapFactory.decodeResource(getResources(), R.drawable.test);
Matrix mat = new Matrix();
mat.postRotate(90);
Bitmap bMapRotate = Bitmap.createBitmap(bMap, 0, 0, bMap.getWidth(), bMap.getHeight(), mat, true);
image.setImageBitmap(bMapRotate);
then your bitmap can be any fancy looking arrow you like.
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
Here is code working perfect for me draw arrow head while drawing line on canvas
package com.example.canvasexample;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.support.annotation.NonNull;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import java.util.ArrayList;
import static android.view.MotionEvent.ACTION_DOWN;
import static android.view.MotionEvent.ACTION_MOVE;
import static android.view.MotionEvent.ACTION_UP;
public class DrawerViewArrow extends View {
private ArrayList<Path> drawingLinePath;
private ArrayList<Path> drawingArrowPath;
private ArrayList<Paint> drawingLinePaint;
private int pathIndex = 0;
private float startX = -1, startY = -1;
private float mX = -1, mY = -1;
public int arrowLength = 80;
public int arrowWidth = 45;
public int strokeWidth = 10;
public DrawerViewArrow(Context context) {
super(context);
initPath();
}
public DrawerViewArrow(Context context, #NonNull AttributeSet attrs) {
super(context, attrs);
initPath();
}
public DrawerViewArrow(Context context, #NonNull AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initPath();
}
private Paint initPaint() {
Paint mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setDither(true);
mPaint.setColor(Color.GREEN);
mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(strokeWidth);
return mPaint;
}
private void initPath() {
drawingLinePath = new ArrayList<>();
drawingArrowPath = new ArrayList<>();
drawingLinePath.add(new Path());
drawingArrowPath.add(new Path());
drawingLinePaint = new ArrayList<>();
drawingLinePaint.add(initPaint());
pathIndex++;
}
private Path createPath(MotionEvent event) {
Path path = new Path();
path.moveTo(event.getX(), event.getY());
return path;
}
private void updateIndex(MotionEvent event) {
if (pathIndex == drawingLinePath.size()) {
drawingLinePath.add(createPath(event));
drawingArrowPath.add(createPath(event));
drawingLinePaint.add(initPaint());
pathIndex++;
}
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (startX > -1 && mX > -1) {
canvas.drawLine(startX, startY, mX, mY, initPaint());
drawArrow(canvas);
}
for (int index = 0; index < pathIndex; index++) {
Path path = drawingLinePath.get(index);
Path arrow_path = drawingArrowPath.get(index);
Paint paint = drawingLinePaint.get(index);
canvas.drawPath(path, paint);
canvas.drawPath(arrow_path, paint);
}
}
private void drawArrow(Canvas canvas) {
double angle = calculateAngle(startX, startY, mX, mY);
float final_angle = (float) (180 - angle);
Path arrow_path = new Path();
Matrix arrow_matrix = new Matrix();
arrow_matrix.postRotate(final_angle, mX, mY);
arrow_path.moveTo(mX, mY);
arrow_path.lineTo(mX - arrowWidth, mY + arrowLength);
arrow_path.moveTo(mX, mY);
arrow_path.lineTo(mX + arrowWidth, mY + arrowLength);
arrow_path.lineTo(mX - (arrowWidth), mY + arrowLength);
arrow_path.transform(arrow_matrix);
canvas.drawPath(arrow_path, initPaint());
}
private void saveArrow() {
if (mX == -1 || mY == -1) {
return;
}
double angle = calculateAngle(startX, startY, mX, mY);
float final_angle = (float) (180 - angle);
Path arrow_path = drawingArrowPath.get(pathIndex - 1);
Matrix arrow_matrix = new Matrix();
arrow_matrix.postRotate(final_angle, mX, mY);
arrow_path.moveTo(mX, mY);
arrow_path.lineTo(mX - arrowWidth, mY + arrowLength);
arrow_path.moveTo(mX, mY);
arrow_path.lineTo(mX + arrowWidth, mY + arrowLength);
arrow_path.lineTo(mX - (arrowWidth), mY + arrowLength);
arrow_path.transform(arrow_matrix);
}
public double calculateAngle(double x1, double y1, double x2, double y2) {
double angle = Math.toDegrees(Math.atan2(x2 - x1, y2 - y1));
angle = angle + Math.ceil(-angle / 360) * 360; //Keep angle between 0 and 360
return angle;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case ACTION_UP:
actionUp(event);
break;
case ACTION_MOVE:
actionMove(event);
break;
case ACTION_DOWN:
actionDown(event);
break;
}
invalidate();
return true;
}
private void actionDown(MotionEvent event) {
updateIndex(event);
startX = event.getX();
startY = event.getY();
}
private void actionMove(MotionEvent event) {
mX = event.getX();
mY = event.getY();
}
private void actionUp(MotionEvent event) {
drawingLinePath.get(pathIndex - 1).lineTo(event.getX(), event.getY());
saveArrow();
startX = -1;
startY = -1;
mX = -1;
mY = -1;
}
}
Use a Path as below and adjust the co-ordinates accordingly:
// Construct a wedge-shaped path
Path mPath = new Path();
mPath.moveTo(0, -50);
mPath.lineTo(-20, 60);
mPath.lineTo(0, 50);
mPath.lineTo(20, 60);
mPath.close();
Copypast from this answer https://stackoverflow.com/a/29383352/9975029
private void fillArrow(Canvas canvas, float x0, float y0, float x1, float y1) {
paint.setStyle(Paint.Style.FILL);
float deltaX = x1 - x0;
float deltaY = y1 - y0;
double distance = Math.sqrt((deltaX * deltaX) + (deltaY * deltaY));
float frac = (float) (1 / (distance / 30));
float point_x_1 = x0 + (float) ((1 - frac) * deltaX + frac * deltaY);
float point_y_1 = y0 + (float) ((1 - frac) * deltaY - frac * deltaX);
float point_x_2 = x1;
float point_y_2 = y1;
float point_x_3 = x0 + (float) ((1 - frac) * deltaX - frac * deltaY);
float point_y_3 = y0 + (float) ((1 - frac) * deltaY + frac * deltaX);
Path path = new Path();
path.setFillType(Path.FillType.EVEN_ODD);
path.moveTo(point_x_1, point_y_1);
path.lineTo(point_x_2, point_y_2);
path.lineTo(point_x_3, point_y_3);
path.lineTo(point_x_1, point_y_1);
path.lineTo(point_x_1, point_y_1);
path.close();
canvas.drawPath(path, paint);
}
Here's my arrow drawing code without using trig functions explicitly (although the underlying math obviously uses trig)
The math makes an arrow head like half of a square (cut diagonally) where variable L is the length of the diagonal. Also, the arrow ends at point p2 which means that for small difference between p2 and p1, the arrow head will be drawn 'before' p2 for sufficient L. Also if p1 and p2 are the same, the arrow will not be drawn because the math would cause division by zero.
I suggest you use Paint.Style.FILL_AND_STROKE to draw this arrow.
I'm open for any questions.
void drawArrow(Canvas canvas, Point p1, Point p2, float L) {
float fsin, fcos;
double d;
if(p1.equals(p2))
return;
d = Math.sqrt(Math.pow(p2.x - p1.x, 2) + Math.pow(p2.y - p1.y, 2));
fsin = (p2.y - p1.y)/(float)d;
fcos = (p2.x - p1.x)/(float)d;
PointF p3 = new PointF(p2.x - L/2*(fsin + fcos), p2.y + L/2*(fcos - fsin));
PointF p4 = new PointF(p2.x + L/2*(fsin - fcos), p2.y - L/2*(fsin + fcos));
canvas.drawLine(p1.x, p1.y, p2.x, p2.y, arrowPaint);
Path path = new Path();
path.setFillType(Path.FillType.EVEN_ODD);
path.moveTo(p2.x, p2.y);
path.lineTo(p3.x, p3.y);
path.lineTo(p4.x, p4.y);
path.close();
canvas.drawPath(path, arrowPaint);
}

Categories

Resources