TransWikia.com

Android correct way to draw vector with stroke width

Stack Overflow Asked by akram on February 22, 2021

Hi I am trying to use a vector drawable in my android app.

Here is the xml for the same

<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="1024dp"
    android:height="1024dp"
    android:viewportWidth="1024"
    android:viewportHeight="1024">
    <path
        android:pathData="M 0,0 L 50,0 L 50,50 z"
        android:strokeColor="#000000" />
</vector>

and here is how it looks without any stroke width
enter image description here

If I add android:strokeWidth="10" here is how it looks
enter image description here

The stoke width is not consistent(same width) across all lines and the leftmost point seems to be not cut off

Is there any way through which all the 3 lines drawn are of consistent(same width) and not irregular?

One Answer

Imagine the drawable as a coordinate system with the point p(0,0) being on the top-left corner. Your x-axis goes from top-left to top-right and your y-axis goes from top-left to bottom-left.

When you're creating a path, it goes from one point to another point in the coordinate system. When you're stroking this path, the drawn line has some strokeWidth which is 1 by default. But when you set the width to, lets say 10, then the line is much thicker in your coordinate-system, but where should this "Thickness" go if your path is, for example already at y=0 ? The drawable won't display any negativate coordinates. That's why your drawable got cut-off.

The solution: add the strokeWidth to the coordinates, that are smaller than strokeWidth + subtract the strokeWidth from the coordinates, that are greater than your viewportWidth-strokeWidth and/or viewportHeight-strokeWidth + give spacing for edges that are at the borders of your viewport (in this example a extra spacing of 3 is fine)

So your code should look like this:

<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="1024dp"
    android:height="1024dp"
    android:viewportWidth="1024"
    android:viewportHeight="1024">
    <path
        android:pathData="M 13,13 L 50,13 L 50,50 z"
        android:strokeColor="#000000"
        android:strokeWidth="10"/>
</vector>

Correct answer by Hannes Mittag on February 22, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP