Creating a Circular Image in Xamarin.Android

If you’re working with mobile applications, sometimes something as simple as creating a circular image can be a bit more time consuming than it should be. Here is the snippet I use to create Circular Images in Xamarin.Android to follow up with my post about Creating Circular Images in XAML.

CircleDrawable:


public class CircleDrawable : Drawable
 {

     Bitmap bmp;
     BitmapShader bmpShader;
     Paint paint;
     RectF oval;

    public CircleDrawable(Bitmap bmp)
     {
         this.bmp = bmp;
         this.bmpShader = new BitmapShader (bmp, Shader.TileMode.Clamp, Shader.TileMode.Clamp);
         this.paint = new Paint () { AntiAlias = true };
         this.paint.SetShader (bmpShader);
         this.oval = new RectF ();
     }

    public override void Draw (Canvas canvas)
     {
         canvas.DrawOval (oval, paint);
     }

    protected override void OnBoundsChange (Rect bounds)
     {
         base.OnBoundsChange (bounds);
         oval.Set (0, 0, bounds.Width (), bounds.Height ());
     }

    public override int IntrinsicWidth
    {
         get
         {
             return bmp.Width;
         }
     }

    public override int IntrinsicHeight {
         get {
             return bmp.Height;
         }
     }

     public override void SetAlpha (int alpha)
     {

     }

    public override int Opacity {
         get {
             return (int)Format.Opaque;
         }
     }

    public override void SetColorFilter (ColorFilter cf)
    {

    }
 }

And here is an example of how to use it:

var bitmap = new Bitmap(); //do something else here to create your bitmap
var circleImage = new CircleDrawable(bitmap);
Advertisements

Creating a Circular Image in XAML

Here is a freeby – my preference for creating circular images in XAML:


<Grid x:Name="SingleImageContainer">
    <Ellipse Height="60" Width="60">
        <Ellipse.Fill>
            <ImageBrush ImageSource="{Binding MyImageUri}" AlignmentX="Center" AlignmentY="Center" />
        </Ellipse.Fill>
    </Ellipse>
 </Grid>

circle (sorry for the bad cropping)