ImageView设置边框的两种方式

MainActivity如下:

package cc.testimageviewbounds;

import android.os.Bundle;
import android.app.Activity;
/**
 * Demo描述:
 * 给ImageView添加边框的两种实现方式
 * 
 * 方式一:
 * 利用自定义的shape-->即此处的imageviewboundshape.xml
 * 且为ImageView设置background,即代码:
 * android:background="@drawable/imageviewboundshape"
 * 
 * 方式二:
 * 自定义ImageView
 *
 */
public class MainActivity extends Activity {
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
	}
}


ImageViewSubClass如下:

package cc.testimageviewbounds;

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 ImageViewSubClass extends ImageView {

	public ImageViewSubClass(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}

	public ImageViewSubClass(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public ImageViewSubClass(Context context) {
		super(context);
	}
	
	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		
		//获取控件需要重新绘制的区域
		Rect rect=canvas.getClipBounds();
		rect.bottom--;
		rect.right--;
		Paint paint=new Paint();
		paint.setColor(Color.RED);
		paint.setStyle(Paint.Style.STROKE);
		paint.setStrokeWidth(3);
		canvas.drawRect(rect, paint);
	}
   
}


main.xml如下:



    
    
    
    


imageviewboundshape.xml如下:


    

   
    
     
    
    
    
    
    
    
    

 

转载于:https://www.cnblogs.com/james1207/p/3290179.html

你可能感兴趣的:(ImageView设置边框的两种方式)