在android中动态更改SVG图像颜色

时间:2014-10-29 09:25:19

标签: android svg imageview android-view svg-filters

我知道使用第三方库,可以在Android中使用SVG图像。 图书馆如:svg-android

加载SVG图像的代码如下:

 public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Create a new ImageView
    ImageView imageView = new ImageView(this);
    // Set the background color to white
    imageView.setBackgroundColor(Color.WHITE);
    // Parse the SVG file from the resource
    SVG svg = SVGParser.getSVGFromResource(getResources(), R.raw.android);
    // Get a drawable from the parsed SVG and set it as the drawable for the ImageView
    imageView.setImageDrawable(svg.createPictureDrawable());
    // Set the ImageView as the content view for the Activity
    setContentView(imageView);
}

工作正常。我能看到图像。但现在我想在运行时更改svg图像的颜色。 为此我尝试了相同项目描述中提到的下面的代码。

  // 0xFF9FBF3B is the hex code for the existing Android green, 0xFF1756c9 is the new blue color
    SVG svg = SVGParser.getSVGFromResource(getResources(), R.raw.android, 0xFF9FBF3B, 0xFF1756c9);

但由于这一点,我无法看到颜色的变化。所以我想知道如何在Java文件中动态更改颜色。

5 个答案:

答案 0 :(得分:26)

我知道这有点晚了但我也遇到了这个问题,并且能够使用setColorFilter(int color, PorterDuff.Mode mode)方法修复此问题。

示例:

 window.onload = function() {

 box2.onmouseover = function(event){
box2.setAttribute("style", "background-color: red;"); 
 }

答案 1 :(得分:10)

我遇到了问题所在。 问题是我在svg文件中使用的颜色代码。 它不完全是 0xFF9FBF3B ,但#9FBF3B
但是在java代码中你必须使用ARGB值(例如0xFF9FBF3B)来编写它。 我已经更新了它,它的工作现在很好。我可以用相同的代码更改svg文件的颜色。

希望这也有助于其他人在运行时更改SVG图像的颜色时识别实际情况。

答案 2 :(得分:1)

Kotlin 中使用@Antlip Dev的答案。

package com.example.... // Your package.

import android.content.Context
import android.graphics.PorterDuff
import android.support.v4.content.ContextCompat
import android.widget.ImageView

class VectorExt

fun ImageView.setSvgColor(color: Int) =
    this.setColorFilter(color, PorterDuff.Mode.SRC_IN)

fun ImageView.setSvgColor(context: Context, color: Int) =
    this.setColorFilter(ContextCompat.getColor(context, color), PorterDuff.Mode.SRC_IN)

用法:

your_image.setSvgColor(ContextCompat.getColor(context!!, R.color.gray))
your_image.setSvgColor(context!!, R.color.gray)

答案 3 :(得分:1)

@Antlip Dev所说的是正确的,但现在不赞成使用该方法。 这是更新的版本:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
    drawable.setColorFilter(new BlendModeColorFilter(color, BlendMode.SRC_ATOP));
} else {
   drawable.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
}

答案 4 :(得分:0)

您可以使用:drawableTint更改颜色

相关问题