自定义View

自定义View分类

  • 自定义View的步骤:
    1.在res/values/中定义View的属性,这里包括字体颜色、修字体大小等
    2.重写View的构造方法,并获取我们在res/values/中自定义的属性
    3.重写onMesure()方法
    4.重写onDraw()方法

时钟案例

  • 1.首先创建一个JAVA类继承于View,里面有四个构造器,一般情况下调用前2个构造器,
  • 2.进行绘制图形操作(详细见代码部分)
  • 3.绘制完成后为了实现秒针、分针和时针的走动,需要不断的向UI线程发送消息从而进行重新绘制,这就需要用到Handler向UI线程不断发送消息,同时不断得到当前系统时间刷新绘图的位置。必须要调用invalidate();方法提醒UI线程进行重新绘制
    4.在布局文件中要调用自定义View需要写上包名+路径,这样才可以被真正的调用

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <com.my.mywidget.widget.MyView
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
LinearLayout>
public class MyView extends View{
    private int width;
    private int heigth;
    private Paint mPaintLine;
    private Paint mPaintCircle;
    private Paint mPaintText;
    private Paint mPaintPoint;
    private Calendar mCalendar;
    public static final int NEED_REFRESH=0x23;
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case NEED_REFRESH:
                    mCalendar=Calendar.getInstance();
                    invalidate();//提醒UI线程重新绘制
                    handler.sendEmptyMessageDelayed(NEED_REFRESH,1000);//相当于迭代,每隔1s就发送一个空消息,告诉UI线程进行重绘操作
                    break;
            }
        }
    };
//    View有4个构造器
    public MyView(Context context) {
        super(context);
    }

    public MyView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mCalendar=Calendar.getInstance();//初始化Calendar,得到当前时间

        mPaintLine=new Paint();
        mPaintLine.setColor(Color.BLACK);//设置颜色
        mPaintLine.setAntiAlias(true);//设置抗锯齿
        mPaintLine.setStrokeWidth(10);//设置线条宽度

        mPaintCircle=new Paint();
        mPaintCircle.setStrokeWidth(10);//设置线条宽度
        mPaintCircle.setColor(Color.BLACK);//设置颜色
        mPaintCircle.setAntiAlias(true);//设置抗锯齿
        mPaintCircle.setStyle(Paint.Style.STROKE);//设置为空心

        mPaintText=new Paint();
        mPaintText.setColor(Color.BLUE);//设置颜色
        mPaintText.setTextAlign(Paint.Align.CENTER);//设置对齐方式
        mPaintText.setAntiAlias(true);//设置抗锯齿
        mPaintText.setTextSize(30);//设置字体大小

        mPaintPoint=new Paint();
        mPaintPoint.setAntiAlias(true);//设置抗锯齿
        mPaintPoint.setStyle(Paint.Style.FILL);//设置为FILL
        mPaintPoint.setStrokeWidth(10);//设置宽度
        mPaintPoint.setColor(Color.BLACK);//设置颜色

        handler.sendEmptyMessage(NEED_REFRESH);//向Handler发送一个空消息
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        width=getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec);//得到系统默认的宽度
        heigth=getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec);//得到系统默认的高度
        setMeasuredDimension(width,heigth);//将默认宽高设置上去
    }
    //onDraw是有UI线程调用,不需要做其他处理
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
//        canvas.drawLine(0,600,600,600,mPaintLine);
//        canvas.drawCircle(300,300,100,mPaintCircle);
        canvas.drawCircle(width/2,heigth/2,300,mPaintCircle);
        canvas.drawCircle(width/2,heigth/2,10,mPaintPoint);
        //利用for循环绘制时钟的时刻信息
        for (int i=1;i<=12;i++){
            // canvas.save();和canvas.restore();需要配合使用
            //先保存,然后进行旋转,然后画线,最后在转到初始位置,
            canvas.save();//保存当前画布状态
            canvas.rotate(360/12*i,width/2,heigth/2);//第一参数代表旋转角度,第二和第三个参数代表旋转中心
            canvas.drawLine(width/2,heigth/2-300,width/2,heigth/2-280,mPaintLine);//前两个表示起始位置,第三和第四个表示末位置,最后一个表示画笔
            canvas.drawText(""+i,width/2,heigth/2-250,mPaintText);//第一个是文本内容,第二和第三个表示显示文本位置
            canvas.restore();//恢复到保存的画布状态
        }

            int minutes = mCalendar.get(Calendar.MINUTE);//得到当前时间的分钟数
            int hours = mCalendar.get(Calendar.HOUR);//得到当前时间的小时数
            int second=mCalendar.get(Calendar.SECOND);//得到当前时间的秒数

            canvas.save();
            Float minutesDegree = minutes / 60f * 360;//得到当前分钟数所占的角度
            canvas.rotate(minutesDegree, width / 2, heigth / 2);
            canvas.drawLine(width / 2, heigth / 2 - 200, width / 2, heigth / 2 + 20, mPaintLine);
            canvas.restore();

            canvas.save();
            Float hoursDegree = (hours * 60 + minutes) / 12f / 60 * 360;//得到当前小时数所占的角度
            canvas.rotate(hoursDegree, width / 2, heigth / 2);
            canvas.drawLine(width / 2, heigth / 2 - 100, width / 2, heigth / 2 + 30, mPaintLine);
            canvas.restore();

            canvas.save();
            Float secondDegree = second/60f*360;//得到当前小时数所占的角度
            canvas.rotate(secondDegree, width / 2, heigth / 2);
            canvas.drawLine(width / 2, heigth / 2 - 240, width / 2, heigth / 2 + 40, mPaintLine);
            canvas.restore();

    }
}

圆形ImageView

package com.xc.xcskin.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

/**
 * 自定义的圆形ImageView,可以直接当组件在布局中使用。
 * @author caizhiming
 *
 */
public class XCRoundImageView extends ImageView{

    private Paint paint ;

    public XCRoundImageView(Context context) {  
        this(context,null);  
    }  

    public XCRoundImageView(Context context, AttributeSet attrs) {  
        this(context, attrs,0);  
    }  

    public XCRoundImageView(Context context, AttributeSet attrs, int defStyle) {  
        super(context, attrs, defStyle); 
        paint = new Paint();

    }  

    /**
     * 绘制圆形图片
     * @author caizhiming
     */
    @Override  
    protected void onDraw(Canvas canvas) {  

        Drawable drawable = getDrawable();  
        if (null != drawable) {  
            Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();  
            Bitmap b = getCircleBitmap(bitmap, 14);  
            final Rect rectSrc = new Rect(0, 0, b.getWidth(), b.getHeight());  
            final Rect rectDest = new Rect(0,0,getWidth(),getHeight());
            paint.reset();  
            canvas.drawBitmap(b, rectSrc, rectDest, paint);  

        } else {  
            super.onDraw(canvas);  
        }  
    }  

    /**
     * 获取圆形图片方法
     * @param bitmap
     * @param pixels
     * @return Bitmap
     * @author caizhiming
     */
    private Bitmap getCircleBitmap(Bitmap bitmap, int pixels) {  
        Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),  
                bitmap.getHeight(), Config.ARGB_8888);  
        Canvas canvas = new Canvas(output);  

        final int color = 0xff424242;

        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());  
        paint.setAntiAlias(true);  
        canvas.drawARGB(0, 0, 0, 0);  
        paint.setColor(color);  
        int x = bitmap.getWidth(); 

        canvas.drawCircle(x / 2, x / 2, x / 2, paint);  
        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));  
        canvas.drawBitmap(bitmap, rect, rect, paint);  
        return output;  


    }  
}

完成这个自定义类后,就可以使用这个类了,就是把这个当组件在布局中使用即可

你可能感兴趣的:(Android)