2015年10月14日 星期三

制作自定義的View1

Create  a MytView class


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
public class MyView extends View {

public MyView(Context context) {//for program use
        super(context);
        init();


    }

  
    public MyView(Context context, AttributeSet attrs) {//for XML use AttributeSet  is the value get from the XML

        super(context, attrs);
        init();

    }

}

Now the View have nothing.

Overide onDraw in MYView class to show something


1
2
3
4
5
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
       Draw something here

    }

remark:in Rect and RectF,the number is coordinate.

Some Draw command


1
2
3
  //First set the paint, paint define the draw style
        paint.setColor(Color.BLUE);
        paint.setTextSize(50);

Draw Text


1
2
3
   //Text
        canvas.drawText("Hello", 0, 70, paint);
        paint.setStyle(Paint.Style.STROKE);

draw Line


1
2
  //draw a Line
        canvas.drawLine(0, 60, 100, 60, paint);
draw Rectangle

1
canvas.drawRect(10, 70, 90, 120, paint);

draw Round Rectangle


1
2
3
 RectF rf = new RectF(10, 130, 90, 160);

     canvas.drawRoundRect(rf, 40, 40, paint);
draw Bitmap


1
2
3
4
 Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.p_04);
//create the 縮略圖
        Bitmap bitmap1 = ThumbnailUtils.extractThumbnail(bitmap, bitmap.getWidth() / 6, bitmap.getHeight() / 6);
        canvas.drawBitmap(bitmap1,10,400,paint);