In my Android App I want to know the distance between the point where the user clicks and a specific VectorDrawable group.
I want the distance to a group like blue
in the VectorDrawable:
<vector android:height="24dp" android:viewportHeight="1052.3622"
android:viewportWidth="744.0945" android:width="24dp" xmlns:android="http://schemas.android.com/apk/res/android">
<path android:fillColor="#ff0000"
android:name="blue"
android:pathData="M182.9,349.5m-74.7,0a74.7,74.7 0,1 1,149.3 0a74.7,74.7 0,1 1,-149.3 0"
android:strokeAlpha="1" android:strokeColor="#000000" android:strokeWidth="4.23501825"/>
<path android:fillColor="#00ff00"
android:name="red"
android:pathData="M474.3,392.4a84.3,102.9 0,1 0,168.6 0a84.3,102.9 0,1 0,-168.6 0z"
android:strokeAlpha="1" android:strokeColor="#000000" android:strokeWidth="5"/>>
</vector>
Is there a straightforward way to calculate this distance in Android?
I am not sure easy method to solve the issue exists but this can be done like this:
Parse vector XML so you have all those variables in runtime. Parsing is not covered here, let's assume you have following data structure that we will work with later:
as you see all fields are hardcoded for simplicity.
Next step is to parse vector path data converting it to android.graphics.Path:
android.util.PathParser is not included, but you can find source here: https://android.googlesource.com/platform/frameworks/base/+/17e64ffd852f8fe23b8e2e2ff1b62ee742af17a6/core/java/android/util/PathParser.java. Not sure how legal it is to copy and use it though.
Having path we will need to find N its points (coordinates). More points - more precise result will be and slower processing:
path - is our path that we get before, iv - is vector container (ImageView, for example), we need it in order to adjust points coordinates. vectorData - is structure that we got before parsing our vector.
Now we need to define region to handle case where path is closed and we want to treat click inside path as 0 distance:
In order to calculate min distance following method should be used: