Issue
I want to draw an image like this in Android
I tried to design the image using a design tool and use it as a Drawable, but it gets pixelated in android.
I use UIBezierPath
to draw it in iOS app
. Is it possible to achieve same thing on Android?
This is what I achieved using XML <layer-list> drawable tag
:
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:height="30dp" android:gravity="top">
<shape android:shape="oval">
<solid android:color="@color/grey" />
</shape>
</item>
<item android:top="30dp" android:bottom="30dp" android:height="100dp" android:width="10dp">
<shape android:shape="rectangle">
<solid android:color="@color/black" />
</shape>
</item>
<item android:height="30dp" android:gravity="bottom">
<shape android:shape="oval">
<solid android:color="@color/white" />
</shape>
</item>
And tried using Paint and Canvas
public class CircleLineImage extends View{
//Setup initial color
private int paintColor = Color.BLACK;
//Defines paint and canvas
private Paint drawPaint;
public CircleLineImage(Context context, AttributeSet attrs) {
super(context, attrs);
setFocusable(true);
setFocusableInTouchMode(true);
setupPaint();
}
private void setupPaint() {
drawPaint = new Paint();
drawPaint.setColor(paintColor);
drawPaint.setAntiAlias(true);
drawPaint.setStrokeWidth(5);
drawPaint.setStyle(Paint.Style.STROKE);
drawPaint.setStrokeJoin(Paint.Join.ROUND);
drawPaint.setStrokeCap(Paint.Cap.ROUND);
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawCircle(0, 0, 10, drawPaint);
canvas.drawLine(5, 10, 12, 200, drawPaint);
canvas.drawCircle(0, 220, 20, drawPaint);
}
}
Thanks.
Solution
Please take a pen and paper and try sketching what you are trying to do when drawing to a canvas. Pen and paper is still the best option to grasp what you want to do.
Content
You have 2 Ovals and a line inbetween. They are all aligned on the same x-Axis value. There should be no change in the x values in your draw*
calls.
Paint
drawPaint.setStyle(Paint.Style.STROKE);
Will not fill. To fill the circles you will need to set FILL
on the paint object.
Cut off circles
Your circles get cut off because you are trying outside the canvas. Again, just sketch things out, your view and canvas have a width and height, use them! Don't just assume arbitrary values for your bounds.
So...
Go and calculate the center of your canvas (e.g. canvas.width() / 2
). The same would go for the y values to evenly distribute and not hard code them.
A somewhat better solution would look something like this:
@Override
protected void onDraw(Canvas canvas) {
drawPaint.setStyle(Paint.Style.FILL);
canvas.drawCircle(centerX, 30, 20, drawPaint);
canvas.drawCircle(centerX, 170, 20, drawPaint);
drawPaint.setStyle(Paint.Style.STROKE);
canvas.drawLine(centerX, 50, centerX, 150, drawPaint);
}
Answered By - David Medenjak
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.