我正在尝试在Canvas上绘制VectorDrawable
资源。我现在这样做的方式有点复杂,所以一步一步的过程看起来像:
从资源加载VectorDrawable
,设置所需的大小,将其转换为位图:
fun getBitmapFromVectorDrawable(context: Context, drawableId: Int, width:
Int, height: Int): Bitmap {
var drawable = ContextCompat.getDrawable(context, drawableId)
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP)
drawable = DrawableCompat.wrap(drawable!!).mutate()
val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
drawable.setBounds(0, 0, width, height)
drawable.isFilterBitmap = true
drawable.draw(canvas)
return bitmap
}
手动夸大此视图:
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="@id/img1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:adjustViewBounds="true"
android:scaleType="fitCenter"/>
...
///ACTUALLY, THIS VIEW IS MORE COMPLICATED WITH TextView AND SOME OTHER VIEWS
</RelativeLayout>
以所需尺寸布局:
val widthSpec = View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.AT_MOST)
val heightSpec = View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.AT_MOST)
view.measure(widthSpec, heightSpec)
view.layout(0, 0, view.measuredWidth, view.measuredHeight)
然后,我将位图设置为此图像查看:
imageView.setImageBitmap(getBitmapFromVectorDrawable(view.context, drawableId, width, height))
然后我使用这种方法将此视图呈现为位图:
fun loadBitmapFromView(v: View, width: Int, height: Int): Bitmap {
v.isDrawingCacheEnabled = true
v.buildDrawingCache();
if (v.drawingCache != null)
return v.drawingCache
val b = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
val c = Canvas(b)
v.draw(c)
return b
}
最后,在画布上画出来:
bitmap = loadBitmapFromView(view, width, height)
matrix.reset()
matrix.postTranslate(translation.left, translation.top)
canvas.drawBitmap(bitmap, matrix, null)
我的测试图片是一个简单的圆圈。如果我试图将其绘制得很小(25px:25px),则边缘上有很多像素伪像。 上面代码中的宽度和高度变量来自drawingRect,我正在尝试在画布上绘制,因此,在第一步,我试图加载目标大小的资源,不需要额外的缩放。 此外,我理解,有一种更好的方法在画布上绘制位图,而不使用视图层次结构,但我需要它来获得一些对齐的好处(在图像中心对齐文本,或使用约束布局,自动调整文本等。 ..)