安卓自訂View實現圖片上傳進度顯示(仿QQ)

來源:互聯網
上載者:User

標籤:自訂view

     首先看下我們想要實現的效果如(qq聊天中發送圖片時的效果):


再看我們實現的效果:



實現原理很簡單,首先我們上傳圖片時需要一個進度值progress,這個不管是自己寫的上傳的方法還是使用第三方開源庫,其次,需要自訂一個View並重寫onDraw方法,此例中的進度是開啟了一個線程,然後模仿進度遞增,然後將進度值通過自訂View調用一個自訂方法傳進自訂View並根據進度進行重繪。

繪製分為三部分:

1.繪製矩形(圖片面積)上半部分陰影區;

2.繪製矩形(圖片面積)下半部分非陰影區;

3.繪製中間進度值(文字);

onDraw代碼:

@Overrideprotected void onDraw(Canvas canvas) {super.onDraw(canvas);        mPaint.setAntiAlias(true); // 消除鋸齒          mPaint.setStyle(Paint.Style.FILL);                 mPaint.setColor(Color.parseColor("#70000000"));//半透明        canvas.drawRect(0, 0, getWidth(), getHeight()-getHeight()*progress/100, mPaint);                mPaint.setColor(Color.parseColor("#00000000"));//全透明        canvas.drawRect(0, getHeight()-getHeight()*progress/100, getWidth(),  getHeight(), mPaint);                mPaint.setTextSize(30);        mPaint.setColor(Color.parseColor("#FFFFFF"));mPaint.setStrokeWidth(2);Rect rect=new Rect();mPaint.getTextBounds("100%", 0, "100%".length(), rect);//確定文字的寬度canvas.drawText(progress+"%", getWidth()/2-rect.width()/2,getHeight()/2, mPaint);        }
傳入進度值的方法:

public void setProgress(int progress){this.progress=progress;postInvalidate();};
主介面調用方法:

customView=(CustomView6) findViewById(R.id.customView);//類比圖片上傳進度new Thread(new Runnable() {@Overridepublic void run() { while (true){   if(progress==100){//圖片上傳完成 handler.sendEmptyMessage(SUCCESS); return; } progress++; customView.setProgress(progress);                    try{                          Thread.sleep(200);  //暫停0.2秒                    } catch (InterruptedException e){                          e.printStackTrace();                      }                  }  }}).start();

demo:http://download.csdn.net/detail/baiyuliang2013/8690773

安卓自訂View實現圖片上傳進度顯示(仿QQ)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.