编辑
如何更改图片颜色(Android)
本文访问次数:0
  1. 1. 项目需求
  2. 2. 更改颜色
  3. 3. 相关函数

项目需求

项目需求为从服务器获取参数,然后更改图片颜色(或者使用代码生成指定形状的drawable,比较麻烦),点击查看iOS下如何操作

更改颜色

//获取图片
Drawable sourceDrawable = ContextCompat.getDrawable(context,R.mipmap.btn_right_arrow_circled);
//将图片转换为Bitmap
Bitmap sourceBitmap = Utils.toBitmap(sourceDrawable);
//生成新的Bitmap
Bitmap finalBitmap = Utils.changeColor(sourceBitmap,Color.parseColor(color));
//设置新的Bitmap
moreImageView.setImageBitmap(finalBitmap);

相关函数

/**
    * Change bitmap`s color.
    * @param sourceBitmap The bitmap.
    * @param color The color.
    * @return The new bitmap.
    */
public static Bitmap changeColor(Bitmap sourceBitmap, int color) {
    Bitmap resultBitmap = Bitmap.createBitmap(sourceBitmap, 0, 0,
            sourceBitmap.getWidth() - 1, sourceBitmap.getHeight() - 1);
    Paint p = new Paint();
    ColorFilter filter = new LightingColorFilter(color, 1);
    p.setColorFilter(filter);

    Canvas canvas = new Canvas(resultBitmap);
    canvas.drawBitmap(resultBitmap, 0, 0, p);
    return resultBitmap;
}

/**
    * Convert bitmap to drawable.
    * @param context The context.
    * @param bitmap The bitmap to be converted.
    * @return The bitmap.
    */
public static Drawable toDrawable(Context context, Bitmap bitmap) {
    return new BitmapDrawable(context.getResources(), bitmap);
}

/**
    * Convert drawable to bitmap.
    * @param drawable The drawable.
    * @return The bitmap.
    */
public static Bitmap toBitmap(Drawable drawable) {
    if (drawable instanceof BitmapDrawable) {
        return ((BitmapDrawable) drawable).getBitmap();
    }

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

    return bitmap;
}
没有任何评论