Skip to content

Instantly share code, notes, and snippets.

@berendn
Last active January 10, 2017 09:46
Show Gist options
  • Save berendn/94d69eeaa414de00ecd6fb076f4d0c30 to your computer and use it in GitHub Desktop.
Save berendn/94d69eeaa414de00ecd6fb076f4d0c30 to your computer and use it in GitHub Desktop.
This ImageView centers the image horizontally. It behaves like gravity:top|center_horizontally if the bitmap is higher than the view, but if the view is higher than the bitmap it behaves like gravity:bottom|center_horizontally. Ideal for images that are positioned below a header text, but should'nt float above the footer.
public class CenterAtBottomImageView extends ImageView {
public CenterAtBottomImageView(Context context) {
super(context);
}
public CenterAtBottomImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CenterAtBottomImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public CenterAtBottomImageView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
protected void onDraw(Canvas canvas) {
if (getBackground() != null) {
getBackground().draw(canvas);
}
if (getDrawable() != null && getDrawable() instanceof BitmapDrawable) {
Bitmap bitmap = ((BitmapDrawable) getDrawable()).getBitmap();
float top = Math.max(0, (getHeight()+getPaddingTop()+getPaddingBottom())-bitmap.getHeight());
float left = Math.max(0, getWidth()*0.5f -(bitmap.getWidth()*0.5f));
canvas.drawBitmap(bitmap, left, top, null);
} else {
super.onDraw(canvas);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment