歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux編程 >> Linux編程

Android開發:Bitmap和canvas的應用

Android開發:Bitmap和canvas的應用
  1. 畫虛線<div>SET_WALLPAPER </div>  
  1.    
  2. public class Canvas extends Activity implements OnTouchListener {  
  3.  /** Called when the activity is first created. */  
  4.  @Override  
  5.  public void onCreate(Bundle savedInstanceState) {  
  6.   super.onCreate(savedInstanceState);  
  7.   this.requestWindowFeature(Window.FEATURE_NO_TITLE);// 去掉標題欄   
  8.   this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,  
  9.     WindowManager.LayoutParams.FLAG_FULLSCREEN);// 去掉信息欄   
  10.   setContentView(R.layout.main);  
  11.   
  12.   iv = new ImageView(this);  
  13.   bitmap = Bitmap.createBitmap(800480, Bitmap.Config.ARGB_8888);  
  14.   iv.setImageBitmap(bitmap);  
  15.   
  16.   LinearLayout ll = (LinearLayout) findViewById(R.id.ll);  
  17.   ll.addView(iv, new LayoutParams(800480));  
  18.   
  19.   ll.setOnTouchListener(this);  
  20.   
  21.  }  
  22. private android.graphics.Canvas myCanvas;  
  23. private Bitmap bitmap;  
  24. private Paint myPaint;  
  25. private ImageView iv;  
  26. private float left;  
  27. private float top;  
  28.  @Override  
  29.  public boolean onTouch(View v, MotionEvent event) {  
  30.   switch (event.getAction()) {  
  31.   case MotionEvent.ACTION_DOWN:  
  32.    myCanvas = new android.graphics.Canvas(bitmap);  
  33.    myPaint = new Paint();  
  34. //   myPaint.setAntiAlias(true);//抗鋸齒   
  35. //      
  36. //   RectF oval = new RectF(0, 0, 200, 200);   
  37. //   myPaint.setColor(Color.DKGRAY);   
  38. //   myCanvas.drawArc(oval, 0, 360, true, myPaint);   
  39. //      
  40. //   myPaint.setColor(Color.LTGRAY);   
  41. //      
  42. //   myCanvas.drawArc(oval, 0, 320, true, myPaint);   
  43.      
  44.      
  45. //   RectF eyes = new RectF(100, 20, 130, 50);   
  46. //   myPaint.setColor(Color.RED);   
  47. //   myCanvas.drawArc(eyes, 0, 360, true, myPaint);   
  48. //   myCanvas.drawCircle(200, 300, 100, myPaint);   
  49.     
  50.    System.out.println("======================");  
  51.    iv.setImageBitmap(bitmap);  
  52.      
  53.    left = event.getX();  
  54.    top  = event.getY();  
  55.      
  56.    break;  
  57.   
  58.   case MotionEvent.ACTION_MOVE:  
  59. //   myCanvas.drawPoint(event.getX(), event.getY(), myPaint);   
  60. //   myPaint.setTypeface(Typeface.createFromFile("/sdcard/stxingka.ttf"));   
  61. //   myPaint.setTextSize(50);   
  62. //   myCanvas.drawText("Hello World!", event.getX(), event.getY(), myPaint);   
  63.       
  64.    PathEffect pathEffect = new DashPathEffect(  
  65.       new float[] { 5555 }, 1);  
  66.    myPaint.setColor(Color.GREEN);  
  67.    myPaint.setPathEffect(pathEffect);  
  68.    myPaint.setStyle(Style.STROKE);  
  69.    myPaint.setStrokeWidth(3);  
  70.    myCanvas.drawARGB(255203041);  
  71.    myCanvas.drawRect(new RectF(left, top, event.getX(), event.getY()),myPaint);  
  72.    iv.setImageBitmap(bitmap);  
  73.    break;  
  74.   case MotionEvent.ACTION_UP:  
  75.    break;  
  76.   }  
  77.   return true;  
  78.  }  

一個讓Gridview項移動的例子:

  1. public class Utils {   
  2.     public static int[] image = { R.drawable.mb5u1_mb5ucom, R.drawable.mb5u2_mb5ucom,  
  3.             R.drawable.mb5u3_mb5ucom, R.drawable.mb5u4_mb5ucom,  
  4.             R.drawable.mb5u5_mb5ucom, R.drawable.mb5u6_mb5ucom,  
  5.             R.drawable.mb5u7_mb5ucom, R.drawable.mb5u8_mb5ucom,  
  6.             R.drawable.mb5u9_mb5ucom, R.drawable.mb5u10_mb5ucom,  
  7.             R.drawable.mb5u11_mb5ucom, R.drawable.mb5u12_mb5ucom,  
  8.             R.drawable.mb5u13_mb5ucom, R.drawable.mb5u14_mb5ucom,  
  9.             R.drawable.mb5u15_mb5ucom, R.drawable.mb5u16_mb5ucom,  
  10.             R.drawable.mb5u17_mb5ucom, R.drawable.mb5u18_mb5ucom,  
  11.             R.drawable.mb5u19_mb5ucom, R.drawable.mb5u20_mb5ucom,  
  12.             R.drawable.mb5u21_mb5ucom, R.drawable.mb5u22_mb5ucom,  
  13.             R.drawable.mb5u23_mb5ucom, R.drawable.mb5u24_mb5ucom,  
  14.             R.drawable.mb5u25_mb5ucom, R.drawable.mb5u26_mb5ucom,  
  15.             R.drawable.mb5u27_mb5ucom, R.drawable.mb5u28_mb5ucom,  
  16.             R.drawable.mb5u29_mb5ucom, R.drawable.mb5u30_mb5ucom,  
  17.             R.drawable.mb5u31_mb5ucom, R.drawable.mb5u32_mb5ucom,  
  18.             R.drawable.mb5u33_mb5ucom, R.drawable.mb5u34_mb5ucom,  
  19.             R.drawable.mb5u35_mb5ucom, R.drawable.mb5u36_mb5ucom,  
  20.             R.drawable.mb5u37_mb5ucom, R.drawable.mb5u38_mb5ucom,  
  21.             R.drawable.mb5u39_mb5ucom, R.drawable.mb5u40_mb5ucom,  
  22.             R.drawable.mb5u41_mb5ucom, R.drawable.mb5u42_mb5ucom,  
  23.             R.drawable.mb5u43_mb5ucom, R.drawable.mb5u44_mb5ucom };  
  24.       
  25.     public static ArrayList<Map<String, Object>> getData() {  
  26.         ArrayList<Map<String, Object>> list = new ArrayList<Map<String, Object>>();  
  27.         for (int i = 0; i < 23; i++) {  
  28.             Map<String, Object> map = new HashMap<String, Object>();  
  29.             map.put("img", image[i]);  
  30.             list.add(map);  
  31.         }  
  32.         return list;  
  33.     }  

正式綁定

  1. public class MyGridViewDemo extends Activity implements OnTouchListener {  
  2.   
  3.     private RelativeLayout myRl;  
  4.     private GridView myGridView;  
  5.     private ArrayList<Map<String, Object>> mArray;  
  6.     private MyAdapter adapter;  
  7.     private int mDragViewX;  
  8.     private int mDragViewY;  
  9.   
  10.     @Override  
  11.     public void onCreate(Bundle savedInstanceState) {  
  12.         super.onCreate(savedInstanceState);  
  13.   
  14.         this.requestWindowFeature(Window.FEATURE_NO_TITLE);// 去掉標題欄   
  15.         this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,  
  16.                 WindowManager.LayoutParams.FLAG_FULLSCREEN);// 去掉信息欄   
  17.   
  18.         setContentView(R.layout.main);  
  19.         myRl = (RelativeLayout) findViewById(R.id.ll);  
  20.         myGridView = new GridView(this);  
  21.         mArray = Utils.getData();  
  22.         System.out.println(mArray.size());  
  23.         adapter = new MyAdapter(this, myGridView.getId(), mArray);  
  24.         myGridView.setAdapter(adapter);  
  25.         // GridView的列數   
  26.         myGridView.setNumColumns(5);  
  27.   
  28.         myRl.addView(myGridView);  
  29.   
  30.         myGridView.setOnTouchListener(this);  
  31.   
  32.     }  
  33.   
  34.     class MyAdapter extends ArrayAdapter<Map<String, Object>> {  
  35.   
  36.         public MyAdapter(Context context, int textViewResourceId,  
  37.                 List<Map<String, Object>> objects) {  
  38.             super(context, textViewResourceId, objects);  
  39.         }  
  40.   
  41.         public ArrayList<Map<String, Object>> getList() {  
  42.             return mArray;  
  43.         }  
  44.   
  45.         public View getView(int position, View convertView, ViewGroup parent) {  
  46.             View row = convertView;  
  47.             if (row == null) {  
  48.                 LayoutInflater inflater = getLayoutInflater();  
  49.   
  50.                 row = (View) inflater.inflate(R.layout.mygrid_item, null);  
  51.             }  
  52.             ImageView imageView = (ImageView) row.findViewById(R.id.img);  
  53.   
  54.             imageView.setImageResource(Integer.valueOf(mArray.get(position)  
  55.                     .get("img").toString()));  
  56.   
  57.             if (from == position) {  
  58.                 imageView.setVisibility(View.INVISIBLE);  
  59.             } else if (View.INVISIBLE == imageView.getVisibility()) {  
  60.                 imageView.setVisibility(View.VISIBLE);  
  61.             }  
  62.               
  63.               
  64.             Log.i("ivan""position =" + position + "aniFrom =" + aniFrom  
  65.                     + "aniTo" + aniTo);  
  66.             Animation ani = null;  
  67.             if (position > aniTo && position <= aniFrom) {  
  68.                 if (position % 5 == 0) {  
  69.                     ani = new TranslateAnimation(3550, -850);  
  70.                 } else {  
  71.                     ani = new TranslateAnimation(-60000);  
  72.                 }  
  73.             } else if (position < aniTo && position >= aniFrom) {  
  74.                 if (position % 5 == 4) {  
  75.                     ani = new TranslateAnimation(-3550850);  
  76.                 } else {  
  77.                     ani = new TranslateAnimation(60000);  
  78.                 }  
  79.             }  
  80.             if (ani != null) {  
  81.                 ani.setAnimationListener(new AnimationListener() {  
  82.                       
  83.                     @Override  
  84.                     public void onAnimationStart(Animation animation) {  
  85.                         // TODO Auto-generated method stub   
  86.                         onAnimation = true;  
  87.                     }  
  88.                     @Override  
  89.                     public void onAnimationRepeat(Animation animation) {  
  90.                         // TODO Auto-generated method stub   
  91.                     }  
  92.                     @Override  
  93.                     public void onAnimationEnd(Animation animation) {  
  94.                         // TODO Auto-generated method stub   
  95.                         onAnimation = false;      
  96.                     }  
  97.                 });  
  98.                 ani.setDuration(500);  
  99.                 imageView.setAnimation(ani);  
  100.             }  
  101.   
  102.             return imageView;  
  103.         }  
  104.   
  105.     }  
  106.     private boolean onAnimation = false;  
  107.     private int from = -1;  
  108.     private int to = -1;  
  109.     private int aniTo;  
  110.     private int aniFrom;  
  111.   
  112.     @Override  
  113.     public boolean onTouch(View v, MotionEvent event) {  
  114.   
  115.         int x = (int) event.getX();  
  116.         int y = (int) event.getY();  
  117.         int position = myGridView.pointToPosition(x, y);  
  118.   
  119.         switch (event.getAction()) {  
  120.         case MotionEvent.ACTION_DOWN:  
  121.   
  122.             // 如果沒有點擊到圖片直接break   
  123.             System.out.println("position =" + position);  
  124.             if (position == -1) {  
  125.                 break;  
  126.             }  
  127.   
  128.             // 獲取到點擊的View   
  129.             View tempView = myGridView.getChildAt(position  
  130.                     - myGridView.getFirstVisiblePosition());  
  131.             System.out.println("tempView =" + tempView);  
  132.             if (tempView == null) {  
  133.                 break;  
  134.             }  
  135.             // 開啟View的緩存   
  136.             tempView.setDrawingCacheEnabled(true);  
  137.             // tempView.getTop()獲取到tempView自身的位置,因為按下的時候應該顯示的位置和他自身的位置相同   
  138.             // tempView.getLeft() 同理   
  139.             startDragging(tempView.getDrawingCache(), tempView.getTop(),  
  140.                     tempView.getLeft());  
  141.   
  142.             // 獲取點擊的位置距所點擊圖片頂部的距離mDragViewX,mDragViewY   
  143.             mDragViewX = x - tempView.getLeft();  
  144.             mDragViewY = y - tempView.getTop();  
  145.   
  146.             from = position;  
  147.             tempView.setVisibility(View.INVISIBLE);  
  148.             break;  
  149.         case MotionEvent.ACTION_MOVE:  
  150.             if (myDragView != null) {  
  151.   
  152.                 RelativeLayout.LayoutParams rllp = (LayoutParams) myDragView  
  153.                         .getLayoutParams();  
  154.                 rllp.leftMargin = x - mDragViewX;  
  155.                 rllp.topMargin = y - mDragViewY;  
  156.                 myDragView.setLayoutParams(rllp);  
  157.             }  
  158.             if (position != -1) {  
  159.                 to = position;  
  160.             }  
  161.             Log.i("ivan""form=" + from);  
  162.             if (from != to && from != -1 && to != -1 &&!onAnimation) {  
  163.   
  164.                 aniFrom = from;  
  165.                 aniTo = to;  
  166.                 Map<String, Object> temp = adapter.getItem(from);  
  167.                 adapter.remove(temp);  
  168.                 adapter.insert(temp, to);  
  169.   
  170.                 from = to;  
  171.   
  172.             }  
  173.   
  174.             break;  
  175.   
  176.         case MotionEvent.ACTION_UP:  
  177.             if (myDragView != null) {  
  178.                 // 把myDragView 從RelativeLayout中刪除   
  179.                 myRl.removeView(myDragView);  
  180.             }  
  181.             // 獲取到松手位置的圖片讓其顯示   
  182.             View end = myGridView.getChildAt(from  
  183.                     - myGridView.getFirstVisiblePosition());  
  184.             if (end != null) {  
  185.                 end.setVisibility(View.VISIBLE);  
  186.             }  
  187.   
  188.             from = -1;  
  189.             to = -1;  
  190.             break;  
  191.   
  192.         }  
  193.   
  194.         return true;  
  195.     }  
  196.   
  197.     private ImageView myDragView;  
  198.   
  199.     private void startDragging(Bitmap tempBitmap, int top, int left) {  
  200.   
  201.         ImageView iv = new ImageView(getApplication());  
  202.         RelativeLayout.LayoutParams rllp = new RelativeLayout.LayoutParams(-2,  
  203.                 -2);  
  204.   
  205.         rllp.leftMargin = left;  
  206.         rllp.topMargin = top;  
  207.         iv.setImageBitmap(tempBitmap);  
  208.         // 測試方法看iv是否有值 作用是讓此View填充全屏   
  209.         // setContentView(iv);   
  210.         myDragView = iv;  
  211.   
  212.         myRl.addView(myDragView, rllp);  
  213.         // 兩種寫法一樣   
  214.         // mDragView.setLayoutParams(rllp);   
  215.         // rl.addView(mDragView);   
  216.   
  217.     }  

---------------------------------------------

dragwindow 圖片拖動

  1. public class DragwindowActivity extends Activity {  
  2.     /** Called when the activity is first created. */  
  3.     @Override  
  4.     public void onCreate(Bundle savedInstanceState) {  
  5.         super.onCreate(savedInstanceState);  
  6.        //setContentView(R.layout.main);   
  7.           
  8.         //設置窗體的屬性   
  9.         WindowManager.LayoutParams params = new LayoutParams();  
  10.         params.height = WindowManager.LayoutParams.FILL_PARENT;  
  11.         params.width = WindowManager.LayoutParams.FILL_PARENT;  
  12.         params.format = PixelFormat.TRANSLUCENT;  
  13.         DisplayMetrics dm = getResources().getDisplayMetrics();  
  14.         final int screenWidth = dm.widthPixels;  
  15.         final int screenHeight = dm.heightPixels-50;  //拖動窗體內的范圍   
  16.           
  17.         //把要拖動view布局文件孵化成view   
  18.         LayoutInflater inflater = LayoutInflater.from(this);  
  19.         View view = inflater.inflate(R.layout.main, null);  
  20.         ImageButton button = (ImageButton) view.findViewById(R.id.ib_tt);  
  21.         button.setOnTouchListener(new OnTouchListener() {  
  22.             int lastX,lastY;  //焦點   
  23.             @Override  
  24.             public boolean onTouch(View v, MotionEvent event) {  
  25.                 int me = event.getAction();  
  26.                 Log.i("TAG""Touch:"+me);  //按下是0,拖動是2,彈起是1;   
  27.                 switch(me){  
  28.                     case MotionEvent.ACTION_DOWN:  
  29.                         lastX  = (int) event.getRawX();  
  30.                         lastY  = (int) event.getRawY();  
  31.                         Log.i("TAG""down x="+lastX+" ,y="+lastY);   
  32.                         break;  
  33.                     case MotionEvent.ACTION_MOVE:  
  34.                         int dx = (int) event.getRawX()-lastX;  
  35.                         int dy = (int) event.getRawY()-lastY;  
  36.                         Log.i("TAG""d x="+dx+" ,d y="+dy);  //拖動的坐標   
  37.                         //拖動移位後的坐標   
  38.                         int left = v.getLeft() + dx;  
  39.                         int top = v.getTop() + dy;  
  40.                         int right = v.getRight() + dx;  
  41.                         int bottom = v.getBottom() + dy;  
  42.                         if(left<0){  
  43.                             left = 0;  
  44.                             right=left+v.getWidth();  
  45.                         }  
  46.                         if(right>screenWidth){  
  47.                             right=screenWidth;  
  48.                             left = right-v.getWidth();  
  49.                         }  
  50.                         if(top<0){  
  51.                             top=0;  
  52.                             bottom = top+v.getHeight();  
  53.                         }  
  54.                         if(bottom>screenHeight){  
  55.                             bottom = screenHeight;  
  56.                             top = bottom - v.getHeight();  
  57.                         }  
  58.                         v.layout(left, top, right, bottom);  
  59.                         lastX  = (int) event.getRawX();  
  60.                         lastY  = (int) event.getRawY();  
  61.                         break;  
  62.                     case MotionEvent.ACTION_UP:  
  63.                         break;  
  64.                 }  
  65.                 return false;  
  66.             }  
  67.         });  
  68.         WindowManager manager = (WindowManager) getSystemService(WINDOW_SERVICE);  
  69.         manager.addView(view, params);     
  70.     }  

----------------------讀取相冊--畫圖保存

  1. ImageView iv1;  
  2. Canvas canvas ;  
  3. Bitmap alteredBitmap;  
  4. /** Called when the activity is first created. */  
  5. @Override  
  6. public void onCreate(Bundle savedInstanceState) {  
  7.     super.onCreate(savedInstanceState);  
  8.     setContentView(R.layout.main);  
  9.     iv1 =(ImageView) findViewById(R.id.iv1);  
  10.     iv1.setOnTouchListener(this);  
  11. }  
  12. public void selectImage(View view) {  
  13.     Intent intent = new Intent(Intent.ACTION_PICK);  
  14.     intent.setType("image/*");  
  15.     startActivityForResult(intent, 200);  
  16. }  
  17. public void saveImage(View view){  
  18.     try {  
  19.         Uri uri = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, new ContentValues());  
  20.         OutputStream os =  getContentResolver().openOutputStream(uri);  
  21.         Boolean result = alteredBitmap.compress(CompressFormat.JPEG, 50, os);  
  22.         if(result){  
  23.             Toast.makeText(this"保存成功"1).show();  
  24.             Intent intent = new Intent(Intent.ACTION_MEDIA_MOUNTED,Uri.parse("file://"+Environment.getExternalStorageDirectory()));  
  25.             sendBroadcast(intent);  
  26.         }else{  
  27.             Toast.makeText(this"保存失敗"1).show();  
  28.         }  
  29.     } catch (FileNotFoundException e) {  
  30.         e.printStackTrace();  
  31.     }  
  32. }  
  33. @Override  
  34. protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
  35.     super.onActivityResult(requestCode, resultCode, data);  
  36.     if (requestCode == 200) {  
  37.         Uri uri = data.getData();  
  38.         try {     
  39.        // InputStream is =getContentResolver().openInputStream(uri);   
  40.             //得到屏幕大小   
  41.         Display currentDisplay = getWindowManager().getDefaultDisplay();  
  42.         int dw = currentDisplay.getWidth();  
  43.         int dh = currentDisplay.getHeight();  
  44.           
  45.         System.out.println(dw+"--"+dh);  
  46.         BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();  
  47.         // 如果設置了injustDecodeBounds這個屬性,不會真的解析bitmap,只返回bitmap的寬高和圖片屬性   
  48.         bmpFactoryOptions.inJustDecodeBounds = true;  
  49.           
  50.         Bitmap bmp = BitmapFactory.decodeFile("/sdcard/066.JPG",  
  51.                 bmpFactoryOptions); //參數傳入只為得到bmp圖屬性 ,再縮小   
  52.         int heightRatio = (int) Math.ceil(bmpFactoryOptions.outHeight  
  53.                 / (float) dh);  
  54.         int widthRatio = (int) Math.ceil(bmpFactoryOptions.outWidth  
  55.                 / (float) dw);  
  56.   
  57.         // 判斷是否要進行縮放   
  58.         if (heightRatio > 1 && widthRatio > 1) {  
  59.             if (heightRatio > widthRatio) {  
  60.                 // 高度變化大,按高度縮放   
  61.                 bmpFactoryOptions.inSampleSize = heightRatio;  
  62.             } else {  
  63.                 // 寬度變化大,按寬度縮放   
  64.                 bmpFactoryOptions.inSampleSize = widthRatio;  
  65.             }  
  66.         }  
  67.         // 把inJustDecodeBounds設置為false,這樣才會真正的decode這個位圖   
  68.             bmpFactoryOptions.inJustDecodeBounds = false;  
  69.             //得到新圖片流   
  70.             InputStream newis = getContentResolver().openInputStream(uri);  
  71.             bmp = BitmapFactory.decodeStream(newis, null, bmpFactoryOptions);  
  72.             // 創建一個bitmap的拷貝   
  73.             // 創建了一個空的bitmap ,用原來的參數填充   
  74.             alteredBitmap = Bitmap.createBitmap(bmp.getWidth(),  
  75.                     bmp.getHeight(), bmp.getConfig());  
  76.             // 創建一個畫布   
  77.             canvas = new Canvas(alteredBitmap);  
  78.             // 創建一個畫筆   
  79.             Paint paint = new Paint();  
  80.             Matrix matrix = new Matrix();  
  81.             canvas.drawBitmap(bmp, matrix, paint);  
  82.             iv1.setImageBitmap(alteredBitmap);  
  83.         } catch (FileNotFoundException e) {  
  84.             e.printStackTrace();  
  85.         }  
  86.     }  
  87. }  
  88. float downx = 0;  
  89. float downy = 0;  
  90. float upx = 0;  
  91. float upy = 0;  
  92. @Override  
  93. public boolean onTouch(View v, MotionEvent event) {  
  94.     int eventtype = event.getAction();  
  95.     Paint paint = new Paint();  
  96.     paint.setColor(Color.GREEN);  
  97.     paint.setStrokeWidth(5);  
  98.     switch (eventtype) {  
  99.     case MotionEvent.ACTION_DOWN:  
  100.         downx = event.getX();  
  101.         downy = event.getY();  
  102.         break;  
  103.     case MotionEvent.ACTION_MOVE:  
  104.         upx = event.getX();  
  105.         upy = event.getY();  
  106.         canvas.drawLine(downx, downy, upx, upy, paint);  
  107.         iv1.invalidate();  
  108.         downx = upx;  
  109.         downy = upy;  
  110.         break;  
  111.     case MotionEvent.ACTION_UP:  
  112.         upx = event.getX();  
  113.         upy = event.getY();  
  114.         canvas.drawLine(downx, downy, upx, upy, paint);  
  115.         iv1.invalidate();  
  116.         break;  
  117.     }  
  118.     return true;  
  119. }  
Copyright © Linux教程網 All Rights Reserved