Reputation: 593
Im trying to draw an arc in android, between two textView using drawArc. My requirement is to achieve an arc as shown in the image which is correct arc shape. But when i tried ,i'm not getting an perfect arc shape and i got the arc which is of semi ovalshaped.
Here is my code snippet:
public class ArcView extends View {
final RectF oval = new RectF();
Path myPath = new Path();
Paint paint;
float left, top, right, bottom;
public FlightStatusArcView(Context context) {
super(context);
}
public FlightStatusArcView(Context context, AttributeSet attrs) {
super(context, attrs);
init(attrs);
}
public FlightStatusArcView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(attrs);
}
private void init(AttributeSet set) {
if (set == null)
return;
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
public void setArcProperties(float l, float t, float r, float b) {
left = l;
top = t;
right = r;
bottom = b;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
oval.set(left, top, right, bottom);
paint.setColor(Color.WHITE);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(5f);
canvas.drawArc(oval, 180f, 180f, false, paint);
drawArrow(canvas);
}
private void drawArrow(Canvas canvas) {
canvas.save();
Paint p = new Paint();
p.setColor(Color.WHITE);
p.setStyle(Paint.Style.FILL);
p.setStrokeWidth(4f);
float startX = oval.left + 20;
float startY = oval.top + (oval.centerY() - oval.top)/ 2;
Path path = new Path();
path.moveTo(startX, startY-20);
path.lineTo(startX + 20, startY + 20);
path.lineTo(startX + 30, startY -17);
path.close();
canvas.drawPath(path, p);
canvas.restore();
}
}
Please help how to achieve the perfect arc shape using the canvas apis.
Upvotes: 1
Views: 466
Reputation: 283
You could use a Path
together with quadTo
or cubicTo
to draw a curve like this. This will allow you to draw quadratic or cubic bezier curves. For instance, a cubic bezier curve with two identical control points (x2, y2)
is constructed like this:
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(5f);
Path p = new Path();
float x1 = 100;
float y1 = 256;
float x2 = 400;
float y2 = 32;
float x3 = 700;
float y3 = 256;
p.moveTo(x1, y1);
p.cubicTo(x2, y2, x2, y2, x3, y3);
canvas.drawPath(p, paint);
drawArrow(canvas);
}
This is the result:
You can find more information on cubicTo
and quadTo
in the official documentation
Upvotes: 1