Shr*_*jan 12 svg android 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);
}
Run Code Online (Sandbox Code Playgroud)
它工作正常.我能看到图像.但现在我想在运行时更改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);
Run Code Online (Sandbox Code Playgroud)
但有了这个,我无法看到颜色的变化.所以我想知道如何在Java文件中动态更改颜色.
小智 27
我知道它有点迟了但我也有这个问题,并且能够使用setColorFilter(int color,PorterDuff.Mode模式)方法解决这个问题.
例:
imageView.setColorFilter(getResources().getColor(android.R.color.black), PorterDuff.Mode.SRC_IN);
Run Code Online (Sandbox Code Playgroud)
Shr*_*jan 10
我到底出了什么问题.问题是我在svg文件中使用的颜色代码.它不完全是0xFF9FBF3B而是#9FBF3B
但是在java代码中你必须用ARGB值写它(例如0xFF9FBF3B).我已经更新了它,它的工作现在很好.我可以用相同的代码更改svg文件的颜色.
希望这也有助于其他人在运行时更改SVG图像的颜色时识别实际情况.
在Kotlin 中使用Antlip Dev的答案。
package com.example.... // Your package.
import android.graphics.PorterDuff
import android.widget.ImageView
import androidx.annotation.ColorRes
import androidx.core.content.ContextCompat
fun ImageView.setSvgColor(@ColorRes color: Int) =
setColorFilter(ContextCompat.getColor(context, color), PorterDuff.Mode.SRC_IN)
Run Code Online (Sandbox Code Playgroud)
用法:
view.your_image.setSvgColor(R.color.gray)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19393 次 |
| 最近记录: |