使用 Android提供的Path實現圖片的截取,重寫View的onTouchEvent方法和onDraw方法,onTouchEvent負責實現截取路徑的構件,onDraw進行刷新頁面,重寫View類的代碼如下 :
- public class MyView extends View {
- private Drawable mDrawable;
- private Path mPath;
- private float mX = -1;
- private float mY = -1;
- private float mPastX;
- private float mPastY;
-
- public MyView(Context context) {
- super(context);
- // TODO Auto-generated constructor stub
- mPath = new Path();
- }
-
- public void setDrawable(Drawable pDrawable){
- mDrawable = pDrawable;
- }
-
- @Override
- protected void onDraw(Canvas canvas) {
- // TODO Auto-generated method stub
- super.onDraw(canvas);
- Log.i("xiao", "onDraw");
- mDrawable.setBounds(0, 0, getWidth(), getHeight());
- Rect lRect = mDrawable.getBounds();
- Log.i("xiao", "lRect.left = " + lRect.left + " top = " + lRect.top + " right = " + lRect.right + " bottom = " + lRect.bottom);
- if(!mPath.isEmpty()){
- Log.i("xiao", "!mPath.isEmpty()");
- canvas.clipPath(mPath);
- //mDrawable.draw(canvas);
- }
-
- mDrawable.draw(canvas);
- }
-
- @Override
- public boolean onTouchEvent(MotionEvent event) {
- // TODO Auto-generated method stub
- Log.i("xiao", "onTouchEvent");
- int lAction = event.getAction();
- if(mX != -1){
- mPastX = mX;
- mPastY = mY;
- }
- mX = event.getX();
- mY = event.getY();
- switch(lAction){
- case MotionEvent.ACTION_DOWN:
- mPath.reset();
- mPath.moveTo(mX, mY);
- break;
- case MotionEvent.ACTION_MOVE:
- mPath.quadTo(mPastX, mPastY, (mX + mPastX) / 2, (mY + mPastY) / 2);
- break;
- case MotionEvent.ACTION_UP:
- mPath.lineTo(mX, mY);
- mX = -1;
- mY = -1;
- invalidate();
- break;
- default:
-
- break;
- }
- return true;
- }
- }
Activity主要負責獲取和設置Drawable和設置布局,代碼如下:
- private MyView mView;
-
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
-
- mView = new MyView(this);
- mView.setDrawable(this.getResources().getDrawable(R.drawable.test1));
- this.setContentView(mView);
- }
未截取時效果:
畫一個路徑截取效果圖:
Android實現圖片按任意路徑截取源碼下載地址:
免費下載地址在 http://linux.linuxidc.com/
用戶名與密碼都是www.linuxidc.com
具體下載目錄在 /2012年資料/9月/13日/Android實現圖片按任意路徑截取