直接看代碼:
1 package shadow.widget;
2
3 import android.content.Context;
4 import android.graphics.Canvas;
5 import android.graphics.Color;
6 import android.graphics.Paint;
7 import android.graphics.Rect;
8 import android.util.AttributeSet;
9 import android.widget.ImageView;
10
11 public class myImageView extends ImageView {
12
13 private String namespace="http://shadow.com";
14 private int color;
15
16 public myImageView(Context context, AttributeSet attrs) {
17 super(context, attrs);
18 // TODO Auto-generated constructor stub
19 color=Color.parseColor(attrs.getAttributeValue(namespace, "BorderColor"));
20 }
21
22 /* (non-Javadoc)
23 * @see android.widget.ImageView#onDraw(android.graphics.Canvas)
24 */
25 @Override
26 protected void onDraw(Canvas canvas) {
27 // TODO Auto-generated method stub
28
29 super.onDraw(canvas);
30 //畫邊框
31 Rect rec=canvas.getClipBounds();
32 rec.bottom--;
33 rec.right--;
34 Paint paint=new Paint();
35 paint.setColor(color);
36 paint.setStyle(Paint.Style.STROKE);
37 canvas.drawRect(rec, paint);
38 }
39 }
這裡要注意的是super.onDraw(canvas);在前,否則邊框可能會被圖片所覆蓋。
xml寫法
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:shadow="http://shadow.com"
android:background="@drawable/bg_newslist"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<RelativeLayout android:id="@id/LinerLayout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<shadow.widget.myImageView
android:id="@id/newsitemPicWithBorder"
shadow:BorderColor="GRAY"
android:layout_width="80px"
android:layout_height="60px"
android:layout_alignParentRight="true"
android:src="@drawable/image_loading"
android:layout_centerInParent="true"
android:layout_marginRight="3px"
></shadow.widget.myImageView>
</LinearLayout>
設置邊框顏色 shadow:BorderColor="GRAY"
myImageView imageView=(myImageView)findViewById(....);
imageView.set....//給imageView賦值