1. 程式人生 > >Android0918(自定義View的屬性,下載顯示球)

Android0918(自定義View的屬性,下載顯示球)

自定義View的屬性

myview_attr.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
  <declare-styleable name="myview">
      <attr name="myviewbackground" format="reference"></attr>
      <attr name="myviewpaintwidth" format="dimension|reference"></attr>
  </declare-styleable
>
</resources>

activity_bitmapview.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:myview="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
android:orientation="vertical">
<Button android:id="@+id/btn_savepicture" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="儲存圖片"/> <com.example.administrator.canvas.widget.MyBitmapView android:id="@+id/bitmapiview"
android:layout_width="wrap_content" android:layout_height="wrap_content" myview:myviewbackground="@mipmap/imagebac" myview:myviewpaintwidth="30dp" />
</LinearLayout>

MyBitmapView.java

public class MyBitmapView extends View {
    private int width;
    private int height;
    private Paint mPaintCircle;
    private Paint mPaintRect;
    private Bitmap mBitmap;
    private Canvas canvasBit;
    private Bitmap bitmapBackground;
    private Matrix matrix;
    public MyBitmapView(Context context) {
        super(context);
    }

    public MyBitmapView(Context context, AttributeSet attrs) {
        super(context, attrs);

        final TypedArray a=context.obtainStyledAttributes(attrs,R.styleable.myview);
        BitmapDrawable dra= (BitmapDrawable) a.getDrawable(R.styleable.myview_myviewbackground);
        if (dra!=null){
            bitmapBackground=dra.getBitmap();
        }else{
            bitmapBackground= BitmapFactory.decodeResource(getResources(), R.mipmap.smallgirl);
        }
        int paintWidth=a.getDimensionPixelOffset(R.styleable.myview_myviewpaintwidth,10);
        mPaintCircle=new Paint();

        mPaintCircle.setColor(Color.GREEN);

        mPaintRect=new Paint();
        mPaintRect.setColor(Color.GREEN);
        mPaintRect.setStrokeCap(Paint.Cap.ROUND);//設定線段開頭的填充形狀,
        //設定結合處的樣子 Miter:結合處為銳角, Round:結合處為圓弧:BEVEL:結合處為直線。
        mPaintRect.setStrokeJoin(Paint.Join.ROUND);//設定線段的中間填充形狀
        mPaintRect.setStrokeWidth(paintWidth);
        mPaintRect.setStyle(Paint.Style.FILL_AND_STROKE);
        //是用來控制繪製輪廓(線條)的方式,一般new一個具體的子類傳入。
//CornerPathEffect:這個類的作用就是將Path的各個連線線段之間的夾角//用一種更平滑的方式連線,類似於圓弧與切線的效果。
//DiscretePathEffect:這個類的作用是打散Path的線段,使得在原來路徑//的基礎上發生打散效果。
//PathDashPathEffect:這個類的作用是使用Path圖形來填充當前的路徑。
        mPaintRect.setPathEffect(new CornerPathEffect(360));
        mPaintRect.setAntiAlias(true);//消鋸齒

        PorterDuffXfermode modeXOR=new PorterDuffXfermode(PorterDuff.Mode.XOR);       
        mPaintRect.setXfermode(modeXOR);
        matrix=new Matrix();
        path=new Path();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        width=getDefaultSize(getSuggestedMinimumWidth(),widthMeasureSpec);
        height=getDefaultSize(getSuggestedMinimumHeight(),heightMeasureSpec);
        setMeasuredDimension(width,height);//設定畫布的大小,長和寬
        mBitmap=Bitmap.createBitmap(width,height,Bitmap.Config.ARGB_8888);
        canvasBit=new Canvas(mBitmap);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

//        canvas.drawBitmap(bitmapBackground,0,0,null);
        canvas.drawBitmap(bitmapBackground, new Rect(0,0,bitmapBackground.getWidth(),bitmapBackground.getHeight()),new Rect(0,0,width,height),null);
        canvasBit.drawRect(0,0,width,height,mPaintCircle);
        canvasBit.drawPath(path,mPaintRect);
        canvas.drawBitmap(mBitmap,0,0,null);


    }
    private Path path;
    private float x,y,old_x,old_y;
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()){
            case MotionEvent.ACTION_MOVE:
                x=event.getX();
                y=event.getY();
                path.moveTo(old_x,old_y);
                path.quadTo((x+old_x)/2,(y+old_y)/2,x,y);
                invalidate();
                old_x=x;
                old_y=y;
                return true;
            case MotionEvent.ACTION_DOWN:
                x=event.getX();
                y=event.getY();
//                path.addCircle(x,y,50,Path.Direction.CW);
                path.moveTo(x,y);
                invalidate();
                old_x=x;
                old_y=y;
                return true;
        }
        return super.onTouchEvent(event);
    }
}

MyBitmapViewACtivity.java

public class MyBitmapViewActivity extends Activity{
    private Button btn_SavePicture;
    private MyBitmapView myBitmapView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bitmapview);
        btn_SavePicture= (Button) findViewById(R.id.btn_savepicture);
        myBitmapView= (MyBitmapView) findViewById(R.id.bitmapiview);
        btn_SavePicture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                myBitmapView.invalidate();
                myBitmapView.setDrawingCacheEnabled(true);
                Bitmap bitmap=myBitmapView.getDrawingCache(true);
                File file=new File(Environment.getExternalStorageDirectory(),System.currentTimeMillis()+".jpg");
                if (!file.exists()){
                    try {
                        file.createNewFile();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                try {
                    bitmap.compress(Bitmap.CompressFormat.JPEG,100,new FileOutputStream(file));
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

這裡寫圖片描述

下載顯示球

activity_bubble.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@mipmap/imagebac">
    <Button
        android:id="@+id/btn_start_download"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"

        android:text="開始下載"/>
<com.example.administrator.canvas.widget.MyBubble
    android:id="@+id/bubble"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"

    />

</LinearLayout>

MyBubble.java

public class MyBubble extends View {
    private int width;
    private int height;
    private Paint mPaintAbove;
    private Paint mPaintBelow;
    private Paint paint;
    private Bitmap mBitmap;
    private Bitmap mBitmapBac;
    private Path path;
    private Canvas mCanvas;

    private int count=0;
    private static final int MESSAGE =0x24;
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch(msg.what){
                case MESSAGE:
                    count+=10;
                    if (count>40) {
                        count = 0;
                    }
                    invalidate();// 重新整理
                    handler.sendEmptyMessageDelayed(MESSAGE,100);
                    break;
            }
        }
    };
    private int currentProgress;
    private float maxProgress=100;
    //得到進度的最大值
    public float getMaxProgress() {
        return maxProgress;
    }
    //設定進度的最大值
    public void setMaxProgress(float maxProgress) {
        this.maxProgress = maxProgress;
    }
    //得到當前的進度值
    public int getCurrentProgress(){
        return currentProgress;
    }
    //設定當前的進度值
    public void setCurrentProgress(int currentProgress){
        this.currentProgress=currentProgress;
        invalidate();//重新整理
        Log.d("當前進度",""+this.currentProgress);

    }

    public MyBubble(Context context) {
        super(context);
    }

    public MyBubble(Context context, AttributeSet attrs) {
        super(context, attrs);

        paint=new Paint();
        paint.setStyle(Paint.Style.FILL);
        paint.setColor(Color.argb(0xff,0x4c,0xaf,0xe9));

        mPaintAbove=new Paint();
        mPaintAbove.setColor(Color.BLACK);
        mPaintAbove.setStyle(Paint.Style.FILL);
        mPaintAbove.setTextSize(50);
        mPaintAbove.setTextAlign(Paint.Align.CENTER);

        mPaintBelow=new Paint();
        mPaintBelow.setColor(Color.argb(0xFF,0xae,0xdc,0xff));
        mPaintBelow.setStyle(Paint.Style.FILL);
        mBitmap= BitmapFactory.decodeResource(getResources(), R.mipmap.imagebac);
        PorterDuffXfermode mode=new PorterDuffXfermode(PorterDuff.Mode.SRC_ATOP);
        paint.setXfermode(mode);
        path=new Path();
        handler.sendEmptyMessageDelayed(MESSAGE,100);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        width=getDefaultSize(getSuggestedMinimumWidth(),widthMeasureSpec);
        height=getDefaultSize(getSuggestedMinimumHeight(),heightMeasureSpec);
        setMeasuredDimension(width,height);//設定畫布的大小,長和寬
        mBitmapBac=Bitmap.createBitmap(width,height,Bitmap.Config.ARGB_8888);
        mCanvas=new Canvas(mBitmapBac);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        path.reset();
        path.moveTo(count+width/8,height/2+width/4-currentProgress/maxProgress*width/2);
        for (int i=0;i<15;i++){
            path.rQuadTo(10,+5,20,-5);
            path.rQuadTo(10,-5,20,+5);
        }
        path.lineTo(count+width/8+600,height/2+width/4-currentProgress/maxProgress*width/2);
        path.lineTo(count+width/8+600,height/2+width/4*3-currentProgress/maxProgress*width/2);
        path.lineTo(count+width/8,height/2+width/4*3-currentProgress/maxProgress*width/2);
        path.close();

        canvas.drawBitmap(mBitmap, 0, 0, null);


        canvas.drawCircle(width / 2, height / 2, width / 4, mPaintAbove);
        mCanvas.drawCircle(width / 2, height / 2, width / 4, mPaintBelow);
        mCanvas.drawPath(path,paint );
        canvas.drawBitmap(mBitmapBac, 0, 0, null);


        canvas.drawText(currentProgress+"%",width/2,height/2,mPaintAbove);
    }
}

MyBubbleActivity.java

public class MyBubbleActivity extends Activity{
    private Button btn_start;
    private static final int PORGRESS=0x25;
    private int progrress;
    private MyBubble myBubble;
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch(msg.what){
                case PORGRESS:
                    progrress++;
                    if (progrress<=100){
                        myBubble.setCurrentProgress(progrress);
                        handler.sendEmptyMessageDelayed(PORGRESS,20);
                    }
                    break;
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bubble);
        myBubble= (MyBubble) findViewById(R.id.bubble);
        btn_start= (Button) findViewById(R.id.btn_start_download);
        btn_start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                handler.sendEmptyMessageDelayed(PORGRESS,10);

            }
        });
    }
}

這裡寫圖片描述