Tester101
Tester101

Reputation: 8172

How can I calculate where to start my line based on the stroke cap?

I'm trying to draw a line, but I need to take the width of the stroke cap into account so I don't overflow the container.

I have code that looks like this...

private void initialize() {
    this.paint = new Paint();
    this.paint.setColor(Color.BLACK);
    this.paint.setStyle(Paint.Style.STROKE);
    this.paint.setStrokeCap(Paint.Cap.ROUND);
    this.paint.setStrokeWidth(1);
}

public void setStrokeWidth(float strokeWidth) {
    this.paint.setStrokeWidth(strokeWidth);
}

public void onDraw(Canvas canvas) {
    int x_start, x_end, y, cap_width;
    y = this.getHeight() / 2;
    x_start = cap_width; //Need to compensate for cap.
    x_end = this.getWidth() - cap_width; //Need to compensate for cap.

    canvas.drawLine(x_start, y, x_end, y, paint);
}

Notice in the onDraw method of the above code, I need to calculate the cap width. How can I calculate this?

Upvotes: 1

Views: 142

Answers (1)

Tester101
Tester101

Reputation: 8172

While writing the question, I realized that the answer may be fairly obvious to some. For those who are not thinking clearly (as I wasn't), here's the solution.

The radius of the cap will always be one half the stroke width.

cap_width = (int)paint.getStrokeWidth / 2;

Upvotes: 2

Related Questions