Issue
I'm trying to eliminate a gap seen below. The View
s are right up against each other so it seems that it is something in the drawable.
I can see that it is related to the width
of the stroke
but how can I eliminate this effect?
Note that this is just an MVCE and the actual use case requires that I use a line smaller than the View
is high.
For the removal of doubt, I will only accept an answer that fixes it in the drawable xml. I don't want a layout driven work around, the layout supplied is just to expose the problem.
drawable/line.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="line">
<stroke
android:width="5dp"
android:color="#ff0000"/>
</shape>
layout/example.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<View
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="@drawable/line">
</View>
<View
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="@drawable/line">
</View>
</LinearLayout>
Solution
Where does this gap come from in Drawable Shape line?
The class responsible for creating shape drawables is GradientDrawable.java
Let's take a look at the source code.
In the draw(Canvas canvas)
method:
switch (st.mShape) {
case LINE: {
RectF r = mRect;
float y = r.centerY();
if (haveStroke) {
canvas.drawLine(r.left, y, r.right, y, mStrokePaint);
}
break;
}
}
A line is drawn from mRect.left
to mRect.right
Now let's see where mRect
is modified.
In the ensureValidRect()
method:
Rect bounds = getBounds();
float inset = 0;
if (mStrokePaint != null) {
inset = mStrokePaint.getStrokeWidth() * 0.5f;
}
final GradientState st = mGradientState;
mRect.set(bounds.left + inset, bounds.top + inset, bounds.right - inset, bounds.bottom - inset);
As you can see an inset
, equal to half the stroke width, is added.
This is where your gap comes from.
how can I eliminate this effect?
You can add your own negative inset (should be half of your stroke width)
drawable/line_inset.xml
<?xml version="1.0" encoding="utf-8"?> <inset xmlns:android="http://schemas.android.com/apk/res/android" android:drawable="@drawable/line" android:insetLeft="-2.5dp" android:insetRight="-2.5dp"/>
Consider using a 9-patch drawable
The lines top and left define the stretch areas. You can see that I'm only stretching the empty space. The lines right and bottom define the content area, in this case, all of the space.
Answered By - Benito Bertoli
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.