Adding border to ImageView

2020-03-26 c# android xml xamarin.android

I am using Xamarin.Android and I want to add a border to a specific side of an ImageView, not through the xml but through the Activity. Is it even possible? And if so, what is the most efficient way? Thanks.

EDIT

enter image description here

Answers

If not using Xml , you can create a custom ImageView to implement it .

MyImageView:

public class MyImageView : ImageView
{
    public MyImageView(Context context, IAttributeSet attrs) :
        base(context, attrs)
    {
        Initialize();
    }

    public MyImageView(Context context, IAttributeSet attrs, int defStyle) :
        base(context, attrs, defStyle)
    {
        Initialize();
    }

    private void Initialize()
    {

    }

    public override void Draw(Canvas canvas)
    {
        base.Draw(canvas);
        // draw border
        Rect rec = canvas.ClipBounds;
        rec.Bottom--;
        rec.Right--;
        Paint paint = new Paint();
        paint.Color = Color.Red; //set color for stroke
        paint.SetStyle(Paint.Style.Stroke);
        paint.StrokeWidth = 5; // set width for stroke 
        canvas.DrawRect(rec, paint);
    }
}

Used in xml :

<ImageView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/imageView1" />
<PorjectNameSpace.MyImageView
    android:layout_gravity="center"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/imageview2"/>

Set image source :

ImageView imageView = FindViewById<ImageView>(Resource.Id.imageView1);
imageView.SetImageResource(Resource.Mipmap.ic_launcher);

MyImageView myImageView = FindViewById<MyImageView>(Resource.Id.imageview2);
myImageView.SetImageResource(Resource.Mipmap.ic_launcher);

The effect :

enter image description here

Related