Last active
August 29, 2015 14:15
-
-
Save alxscms/344de03f9bc7e77d7cce to your computer and use it in GitHub Desktop.
An image view with an inner stroke overlaying the actual image
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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