LuckyLuke
LuckyLuke

Reputation: 49077

Custom view does not draw correctly

I am just trying to create a horizontal line. I have painted the view red and then added a blue line which I thought should take half the height.

Since I say that my custom view is 40 dp in height I would have thought that the blue bar with 20 dp in height would fill it half ways. But it doesn't. It takes 1/4 instead of 1/2. How can I fix that?

public class MyProgressView extends View {

    public MyProgressView(Context context) {
        super(context);
    }

    public MyProgressView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        Paint paint = new Paint();
        paint.setColor(Color.BLUE);
        paint.setStrokeWidth(dipToPx(20));
        canvas.drawLine(0, 0, 300, 0, paint);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int parentWidth = MeasureSpec.getSize(widthMeasureSpec);

        setMeasuredDimension(parentWidth, dipToPx(40));
    }

    private int dipToPx(int dp) {
        return (int) getResources().getDisplayMetrics().density * dp;
    }
}

and XML:

<view
        class="com.company.MyProgressView"
        android:background="#ff0000"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        />

Upvotes: 0

Views: 66

Answers (1)

Devrim
Devrim

Reputation: 15533

In your case drawLine method draws a line on Y=0. This means your line's center position on Y is 0. If you set stroke width to 20, it is going to fill -10 and +10.

There are 2 different solutions:

  1. You can set stroke with to 40(which will fill -20 and +20)
  2. You can set your Y to 10 on your drawLine method(which will fill 0 and +20).

Upvotes: 1

Related Questions