Skip to content

Instantly share code, notes, and snippets.

@behumble
Last active July 7, 2016 11:49
Show Gist options
  • Save behumble/46a5f24b204203e0dadb to your computer and use it in GitHub Desktop.
Save behumble/46a5f24b204203e0dadb to your computer and use it in GitHub Desktop.
Drawable implementation which draws a chess board to express transparency
package com.thinkfree.touchspan;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
/**
* @author Alan Goo(behumble@hanjava.net)
*/
public class ChessBoardDrawable extends Drawable {
public static final int LIGHTGRAY = 0xFFDDDDDD;
public static final int DARKGRAY = 0xFF222222;
private int thinknessPx;
private Paint bgPaint = new Paint();
private Paint fgPaint = new Paint();
public ChessBoardDrawable(int thinknessPx) {
this.thinknessPx = thinknessPx;
bgPaint.setColor(Color.WHITE);
fgPaint.setColor(LIGHTGRAY);
}
public void adjustFor(int textColor) {
// perceived brightness
// http://stackoverflow.com/a/12043228/111890
int r = Color.red(textColor);
int g = Color.green(textColor);
int b = Color.blue(textColor);
double luma = 0.2126 * r + 0.7152 * g + 0.0722 * b;
boolean textDark = luma < 128;
if (textDark) {
bgPaint.setColor(Color.WHITE);
fgPaint.setColor(LIGHTGRAY);
} else {
bgPaint.setColor(Color.BLACK);
fgPaint.setColor(DARKGRAY);
}
invalidateSelf();
}
@Override
public void draw(Canvas canvas) {
canvas.drawPaint(bgPaint);
Rect b = getBounds();
int twiceThickness = thinknessPx << 1;
boolean flipper = true;
for (int x = b.left; x < b.right; x += thinknessPx) {
int offset = flipper ? 0 : thinknessPx;
for (int y = b.top; y < b.bottom; y += twiceThickness) {
canvas.drawRect(x, y + offset, x + thinknessPx, y + offset + thinknessPx, fgPaint);
}
flipper = !flipper;
}
}
@Override
public void setAlpha(int i) {
// just ignore
}
@Override
public void setColorFilter(ColorFilter colorFilter) {
// just ignore
}
@Override
public int getOpacity() {
return PixelFormat.OPAQUE;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment