为ImageView添加边框

时间:2020-03-26 12:12:37

标签: c# android xml xamarin.android

我正在使用Xamarin.Android,我想向ImageView的特定一侧添加边框,而不是通过xml,而是通过Activity。 可能吗如果是这样,最有效的方法是什么? 谢谢。

编辑

enter image description here

1 个答案:

答案 0 :(得分:0)

如果不使用Xml,则可以创建自定义ImageView来实现它。

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);
    }
}

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"/>

设置图像源:

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);

效果:

enter image description here