Android ImageView加边框

Android 给ImageView加边框一般有两种方式:一种是自定义shap,将ImageView的背景设置为此shap;另一种方式设置是自定义ImageView,在OnDraw方法当中绘制边框。以上两种方法都可以实现添加边框的功能,但是第一种方法比较快捷方便,还可以使用shap的其他属性例如圆角,推荐使用。

1,使用shap,自定义的shap

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" 
    android:shape="rectangle">
    <!-- 设置边框的宽度和颜色 -->
    <stroke android:width="3dp" android:color="@color/orange"/>
    <!-- 设置框内的填充色  -->
    <solid android:color="@android:color/transparent"/>
    <!-- 设置圆角 -->
    <corners android:radius="5dip"/>
    <!-- 设置内边距 -->
    <padding android:left="2dp"
        android:top="2dp"
        android:right="2dp"
        android:bottom="2dp"
        ></padding>
    
</shape>
2,使用自定义ImageView

package com.example.activityanimationdemo;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.widget.ImageView;

public class MyImageView extends ImageView{

	public MyImageView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		// TODO Auto-generated constructor stub
	}

	public MyImageView(Context context, AttributeSet attrs) {
		super(context, attrs);
		// TODO Auto-generated constructor stub
	}

	public MyImageView(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
	}

	@Override
	protected void onDraw(Canvas canvas) {
		// TODO Auto-generated method stub
		super.onDraw(canvas);
		//获取控件需要重新绘制的区域  
        Rect rect=canvas.getClipBounds();  
        rect.bottom-=4;  
        rect.right-=4; 
        rect.left+=4;
        rect.top+=4;
        Paint paint=new Paint();  
        paint.setColor(Color.RED);  
        paint.setStyle(Paint.Style.STROKE);  
        paint.setStrokeWidth(4);  
        canvas.drawRect(rect, paint);
	}

}
说明 :在使用自定义控件的时候 rect的边界坐标变化最好与宽度保持一致防止出现四周边框宽度不统一的情况出现。


你可能感兴趣的:(android,imageview,添加边框的另种方法)