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 {@Overrideprotected 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);}@Overrideprotected 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如下:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="给ImageView添加边框的两种方式" android:layout_centerHorizontal="true" android:layout_marginTop="65dip" /> <ImageView android:id="@+id/firstImageView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/ic_launcher" android:layout_centerHorizontal="true" android:layout_marginTop="150dip" android:background="@drawable/imageviewboundshape" /> <cc.testimageviewbounds.ImageViewSubClass android:id="@+id/secondImageView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/ic_launcher" android:layout_centerHorizontal="true" android:layout_marginTop="250dip" /> </RelativeLayout>
imageviewboundshape.xml如下:
<?xml version="1.0" encoding="utf-8"?> <!-- 定义矩形rectangle --><shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" > <!-- 设置边框的大小和颜色 --> <stroke android:width="3dip" android:color="#ff0000" /> <!-- 设置矩形内的颜色,此处为透明色 --> <solid android:color="@android:color/transparent"/> <!-- 定义圆角弧度 --> <corners android:bottomLeftRadius="4dp" android:bottomRightRadius="4dp" android:topLeftRadius="4dp" android:topRightRadius="4dp" /> </shape>