Issue
I've created a class that extends Shape
in order to draw custom shapes (rectangle with cut off corners) for the background of my buttons. The problem I have is that lines drawn as a diagonal appear much thicker than straight lines:
How can I make it so the border is always a consistent width? I tried setting anti-aliasing to true/false but that made no difference
public class ShapeMaker extends Shape {
private float STROKE_WIDTH = 20.0f;
private final Paint border = new Paint();
private final Path path;
private float tl = 0; //Top Left
private float tr = 0; //Top Right
private float bl = 0; //Bottom Left
private float br = 0; //Bottom Right
public ShapeMaker(float tl, float tr, float bl, float br, int fillColor) {
path = new Path();
this.tl = tl;
this.tr = tr;
this.bl = bl;
this.br = br;
border.setColor(fillColor);
border.setStyle(Paint.Style.STROKE);
border.setStrokeWidth(STROKE_WIDTH);
border.setAntiAlias(true);
border.setDither(true);
border.setStrokeJoin(Paint.Join.ROUND);
border.setStrokeCap(Paint.Cap.ROUND);
}
@Override
protected void onResize(float width, float height) {
super.onResize(width, height);
path.reset();
path.moveTo(0 + tl, 0);
path.lineTo(width - tr, 0);
path.lineTo(width, tr);
path.lineTo(width, height-br);
path.lineTo(width-br, height);
path.lineTo(0+bl, height);
path.lineTo(0, height-bl);
path.lineTo(0, 0+tl);
path.lineTo(0 + tl, 0);
path.close();
}
@Override
public void draw(Canvas canvas, Paint paint) {
canvas.drawPath(path, border);
}
}
Usage:
Button button = findViewById(R.id.buttom);
float den = getResources().getDisplayMetrics().density;
button.setBackground(new ShapeDrawable(new ShapeMaker(den * 15, 0, 0, 0, Color.RED)));
Solution
The short answer is to "move" your line inwards (away from the edge of the view) by an amount equal to half the stroke width.
Your path traces the exact edge of your view. When the stroke is actually drawn, it is centered on this path. This means that half of the stroke is outside the view's bounds, and is therefore clipped.
However, when you draw the diagonal portion of the path, you're drawing entirely within the view's bounds, so no clipping takes place. This makes the diagonal stroke appear to be twice as thick as the rest.
Here's my equivalent for the code you wrote:
int inset = (int) border.getStrokeWidth() / 2;
path.reset();
path.moveTo(notch + inset, inset);
path.lineTo(width - inset, inset);
path.lineTo(width - inset, height - inset);
path.lineTo(inset, height - inset);
path.lineTo(inset, notch + inset);
path.close();
Answered By - Ben P.
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.