使用XML在android中绘制自定义形状 [英] Draw a custom shape in android using XML
问题描述
我正在向Android地图视图添加自定义标记。这是我正在使用的图像。当放置更多标记时,例如大约100个标记,整个应用程序变得越来越慢。这是我正在使用的图像。
我计划不使用此图像,而是将其绘制为XML形状。怎么做?
我也在关注
I am adding a custom marker to the android map view. here is the image I am using for it.It looks like as more markers are placed say about 100 the entire app is getting slow. Here is the image I am using for that.
Instead of using this image, I am planning to draw this image as a shape in XML. How to do that?
Also I am following this tutorial to display a custom marker. Is this custom drawing delaying the app?
Whats the best way to do it?
It's possible, but looks like does not make sense. Because Google Map requires only bitmap. So you need create bitmap and draw your shape with help of canvas.
marker.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:width="20dp"
android:height="20dp"
android:top="10dp">
<rotate
android:fromDegrees="45"
android:pivotX="75%"
android:pivotY="40%">
<shape>
<solid android:color="#fe696d" />
</shape>
</rotate>
</item>
<item
android:width="@dimen/marker_width"
android:height="@dimen/marker_height"
android:bottom="8dp">
<shape>
<solid android:color="#4b4b4b" />
<corners
android:topLeftRadius="@dimen/marker_corner_radius"
android:topRightRadius="4dp" />
</shape>
</item>
<item
android:width="32dp"
android:height="26dp"
android:bottom="4dp"
android:top="16dp">
<shape>
<solid android:color="#fe696d" />
<corners
android:bottomLeftRadius="@dimen/marker_corner_radius"
android:bottomRightRadius="@dimen/marker_corner_radius" />
</shape>
</item>
dimen.xml
<resources>
<dimen name="marker_corner_radius">4dp</dimen>
<dimen name="marker_height">40dp</dimen>
<dimen name="marker_width">32dp</dimen>
</resources>
part of code to convert shape into bitmap (from fragment/activity with Map)
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
Drawable drawable = ResourcesCompat.getDrawable(getResources(), R.drawable.marker, null);
Canvas canvas = new Canvas();
int width = getResources().getDimensionPixelOffset(R.dimen.marker_width);
int height = getResources().getDimensionPixelOffset(R.dimen.marker_height);
drawable.setBounds(0, 0, width, height);
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
canvas.setBitmap(bitmap);
drawable.draw(canvas);
BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromBitmap(bitmap);
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().icon(bitmapDescriptor).position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
result would be next
这篇关于使用XML在android中绘制自定义形状的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!