Skip to content

Instantly share code, notes, and snippets.

@alxscms
Last active August 29, 2015 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alxscms/344de03f9bc7e77d7cce to your computer and use it in GitHub Desktop.
Save alxscms/344de03f9bc7e77d7cce to your computer and use it in GitHub Desktop.
An image view with an inner stroke overlaying the actual image
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.widget.ImageView;
public class StrokeOverlayImageView extends ImageView {
private final int DEFAULT_BORDER_COLOR = 0x26000000;
private final int DEFAULT_BORDER_WIDTH = 1; // width in pixels
private Paint mBorderPaint;
private Rect mBorderBounds;
public StrokeOverlayImageView(Context context) {
super(context);
init();
}
public StrokeOverlayImageView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public StrokeOverlayImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
mBorderPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mBorderPaint.setStyle(Paint.Style.STROKE);
mBorderPaint.setColor(DEFAULT_BORDER_COLOR);
mBorderPaint.setStrokeWidth(DEFAULT_BORDER_WIDTH * 2); // the stroke is centered, so we multiply by two to have the right inner stroke width
mBorderBounds = new Rect();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
mBorderBounds.set(
getPaddingLeft(),
getPaddingTop(),
getMeasuredWidth() - getPaddingRight(),
getMeasuredHeight() - getPaddingBottom()
);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawRect(mBorderBounds, mBorderPaint);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment