Skip to content

Instantly share code, notes, and snippets.

@lurbas
Last active July 14, 2023 02:13
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save lurbas/bde6211a52f867cc5583dfa74ebda569 to your computer and use it in GitHub Desktop.
Save lurbas/bde6211a52f867cc5583dfa74ebda569 to your computer and use it in GitHub Desktop.
Duotone ColorFilter for Android
public ColorFilter duotoneColorFilter(@ColorInt int colorBlack, @ColorInt int colorWhite, float contrast) {
ColorMatrix cm = new ColorMatrix();
ColorMatrix cmBlackWhite = new ColorMatrix();
float lumR = 0.2125f;
float lumG = 0.7154f;
float lumB = 0.0721f;
float[] blackWhiteArray = new float[]{
lumR, lumG, lumB, 0, 0,
lumR, lumG, lumB, 0, 0,
lumR, lumG, lumB, 0, 0,
0, 0, 0, 1, 0};
cmBlackWhite.set(blackWhiteArray);
ColorMatrix cmContrast = new ColorMatrix();
float scale = contrast + 1.0f;
float translate = (-0.5f * scale + 0.5f) * 255f;
float[] contrastArray = new float[]{
scale, 0, 0, 0, translate,
0, scale, 0, 0, translate,
0, 0, scale, 0, translate,
0, 0, 0, 1, 0};
cmContrast.set(contrastArray);
ColorMatrix cmDuoTone = new ColorMatrix();
float r1 = Color.red(colorWhite);
float g1 = Color.green(colorWhite);
float b1 = Color.blue(colorWhite);
float r2 = Color.red(colorBlack);
float g2 = Color.green(colorBlack);
float b2 = Color.blue(colorBlack);
float r1r2 = (r1 - r2) / 255f;
float g1g2 = (g1 - g2) / 255f;
float b1b2 = (b1 - b2) / 255f;
float[] duoToneArray = new float[]{
r1r2, 0, 0, 0, r2,
g1g2, 0, 0, 0, g2,
b1b2, 0, 0, 0, b2,
0, 0, 0, 1, 0};
cmDuoTone.set(duoToneArray);
cm.postConcat(cmBlackWhite);
cm.postConcat(cmContrast);
cm.postConcat(cmDuoTone);
return new ColorMatrixColorFilter(cm);
}
@chris95x8
Copy link

Any way this could be applied to a Paint which is then drawn on a Canvas?
Doing it like this makes the Bitmap solid colorBlack, or dark_purple in this case.

Canvas duotoneCanvas = new Canvas(mutableBitmap); Paint duotonePaint = new Paint(); ColorFilter duotoneFilter = duotoneColorFilter( ContextCompat.getColor(context, R.color.dark_purple), ContextCompat.getColor(context, R.color.bright_red), 0 ); duotonePaint.setColorFilter(duotoneFilter); duotoneCanvas.drawPaint(duotonePaint);

@thaiduong1995
Copy link

tks bro

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment