【问题标题】:resize vectordrawable icon programmatically以编程方式调整vectordrawable图标的大小
【发布时间】:2017-07-12 17:04:51
【问题描述】:

我在我的 android 项目中动态显示了一些 VectorDrawable 图标。 但是,我无法使用以下代码缩放 java 层中的图标:

VectorDrawable jDrawable = (VectorDrawable) getContext().getDrawable(nResourceID);

// resize the icon
jDrawable.setBounds(30, 30, 30, 30);

// set the icon in the button view
button.setCompoundDrawablesRelativeWithIntrinsicBounds(jDrawable, null, null, null);

注意Android how to resize (scale) an xml vector icon programmatically的答案并没有解决我的问题。

【问题讨论】:

  • 你误会了!抱歉不完整。

标签: java android android-vectordrawable


【解决方案1】:

jDrawable.setBounds 因 android 中的错误而无法工作。

克服该错误的一种方法是将VectorDrawable 转换为Bitmap 并显示它。

Bitmap bitmap = Bitmap.createBitmap(jDrawable.getIntrinsicWidth(), jDrawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
jDrawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
jDrawable.draw(canvas);

然后使用bitmap 显示如下所示的内容。先转换成BitmapDrawable

BitmapDrawable bd = new BitmapDrawable(bitmap);
buttonsetCompoundDrawablesRelativeWithIntrinsicBounds(bd, null, null, null);

你也可以在你的辅助函数中返回bd

要在 pre-23 API 上使用它,请将其放入 build.gradle

vectorDrawables.useSupportLibrary = true 

【讨论】:

  • 总是得到预期的结果!
【解决方案2】:

至少 API > 21 更容易。 假设我们从资源中有 VectorDrawable(检索它的示例代码):

val iconResource = context.resources.getIdentifier(name, "drawable", context.packageName)
val drawable = context.resources.getDrawable(iconResource, null)

对于 VectorDrawable,只需设置所需的大小:

drawable.setBounds(0, 0, size, size)

并在按钮中显示drawable:

button.setCompoundDrawables(null, drawable, null, null)

就是这样。但请注意使用 setCompoundDrawables(不是 Intrinsic 版本)!

【讨论】:

    猜你喜欢
    • 2011-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多