Skip to content

Instantly share code, notes, and snippets.

@justintoth
Created September 17, 2014 17:28
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 justintoth/bbe22db3375dc1764126 to your computer and use it in GitHub Desktop.
Save justintoth/bbe22db3375dc1764126 to your computer and use it in GitHub Desktop.
Xamarin - Center Button Text + Left Drawable
public class CenteredButtonDrawable : Button {
private static int LEFT = 0, TOP = 1, RIGHT = 2, BOTTOM = 3;
// Pre-allocate objects for layout measuring
private Rect textBounds = new Rect();
private Rect drawableBounds = new Rect();
public CenteredButtonDrawable(Context context) : base(context, null) {
}
public CenteredButtonDrawable(Context context, IAttributeSet attrs) : base(context, attrs) {
}
public CenteredButtonDrawable(Context context, IAttributeSet attrs, int defStyle) : base(context, attrs, defStyle) {
}
protected override void OnLayout(bool changed, int left, int top, int right, int bottom) {
base.OnLayout(changed, left, top, right, bottom);
if (!changed) return;
var text = this.Text;
if (!System.String.IsNullOrEmpty(text)) {
var textPaint = this.Paint;
textPaint.GetTextBounds(text, 0, text.Length, textBounds);
} else {
textBounds.SetEmpty ();
}
var width = this.Width - (this.PaddingLeft + this.PaddingRight);
var drawables = this.GetCompoundDrawables ();
if (drawables[LEFT] != null) {
drawables[LEFT].CopyBounds(drawableBounds);
int leftOffset =
(width - (textBounds.Width () + drawableBounds.Width ()) + this.RightPaddingOffset) / 2 - this.CompoundDrawablePadding;
drawableBounds.Offset(leftOffset, 0);
drawables [LEFT].Bounds = drawableBounds;
}
if (drawables[RIGHT] != null) {
drawables[RIGHT].CopyBounds(drawableBounds);
int rightOffset =
((textBounds.Width () + drawableBounds.Width ()) - width + this.LeftPaddingOffset) / 2 + this.CompoundDrawablePadding;
drawableBounds.Offset(rightOffset, 0);
drawables[RIGHT].Bounds = drawableBounds;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment