Android開發:Bitmap和canvas的應用
- 畫虛線<div>SET_WALLPAPER </div>
-
- public class Canvas extends Activity implements OnTouchListener {
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- this.requestWindowFeature(Window.FEATURE_NO_TITLE);// 去掉標題欄
- this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
- WindowManager.LayoutParams.FLAG_FULLSCREEN);// 去掉信息欄
- setContentView(R.layout.main);
-
- iv = new ImageView(this);
- bitmap = Bitmap.createBitmap(800, 480, Bitmap.Config.ARGB_8888);
- iv.setImageBitmap(bitmap);
-
- LinearLayout ll = (LinearLayout) findViewById(R.id.ll);
- ll.addView(iv, new LayoutParams(800, 480));
-
- ll.setOnTouchListener(this);
-
- }
- private android.graphics.Canvas myCanvas;
- private Bitmap bitmap;
- private Paint myPaint;
- private ImageView iv;
- private float left;
- private float top;
- @Override
- public boolean onTouch(View v, MotionEvent event) {
- switch (event.getAction()) {
- case MotionEvent.ACTION_DOWN:
- myCanvas = new android.graphics.Canvas(bitmap);
- myPaint = new Paint();
- // myPaint.setAntiAlias(true);//抗鋸齒
- //
- // RectF oval = new RectF(0, 0, 200, 200);
- // myPaint.setColor(Color.DKGRAY);
- // myCanvas.drawArc(oval, 0, 360, true, myPaint);
- //
- // myPaint.setColor(Color.LTGRAY);
- //
- // myCanvas.drawArc(oval, 0, 320, true, myPaint);
-
-
- // RectF eyes = new RectF(100, 20, 130, 50);
- // myPaint.setColor(Color.RED);
- // myCanvas.drawArc(eyes, 0, 360, true, myPaint);
- // myCanvas.drawCircle(200, 300, 100, myPaint);
-
- System.out.println("======================");
- iv.setImageBitmap(bitmap);
-
- left = event.getX();
- top = event.getY();
-
- break;
-
- case MotionEvent.ACTION_MOVE:
- // myCanvas.drawPoint(event.getX(), event.getY(), myPaint);
- // myPaint.setTypeface(Typeface.createFromFile("/sdcard/stxingka.ttf"));
- // myPaint.setTextSize(50);
- // myCanvas.drawText("Hello World!", event.getX(), event.getY(), myPaint);
-
- PathEffect pathEffect = new DashPathEffect(
- new float[] { 5, 5, 5, 5 }, 1);
- myPaint.setColor(Color.GREEN);
- myPaint.setPathEffect(pathEffect);
- myPaint.setStyle(Style.STROKE);
- myPaint.setStrokeWidth(3);
- myCanvas.drawARGB(255, 20, 30, 41);
- myCanvas.drawRect(new RectF(left, top, event.getX(), event.getY()),myPaint);
- iv.setImageBitmap(bitmap);
- break;
- case MotionEvent.ACTION_UP:
- break;
- }
- return true;
- }
一個讓Gridview項移動的例子:
- public class Utils {
- public static int[] image = { R.drawable.mb5u1_mb5ucom, R.drawable.mb5u2_mb5ucom,
- R.drawable.mb5u3_mb5ucom, R.drawable.mb5u4_mb5ucom,
- R.drawable.mb5u5_mb5ucom, R.drawable.mb5u6_mb5ucom,
- R.drawable.mb5u7_mb5ucom, R.drawable.mb5u8_mb5ucom,
- R.drawable.mb5u9_mb5ucom, R.drawable.mb5u10_mb5ucom,
- R.drawable.mb5u11_mb5ucom, R.drawable.mb5u12_mb5ucom,
- R.drawable.mb5u13_mb5ucom, R.drawable.mb5u14_mb5ucom,
- R.drawable.mb5u15_mb5ucom, R.drawable.mb5u16_mb5ucom,
- R.drawable.mb5u17_mb5ucom, R.drawable.mb5u18_mb5ucom,
- R.drawable.mb5u19_mb5ucom, R.drawable.mb5u20_mb5ucom,
- R.drawable.mb5u21_mb5ucom, R.drawable.mb5u22_mb5ucom,
- R.drawable.mb5u23_mb5ucom, R.drawable.mb5u24_mb5ucom,
- R.drawable.mb5u25_mb5ucom, R.drawable.mb5u26_mb5ucom,
- R.drawable.mb5u27_mb5ucom, R.drawable.mb5u28_mb5ucom,
- R.drawable.mb5u29_mb5ucom, R.drawable.mb5u30_mb5ucom,
- R.drawable.mb5u31_mb5ucom, R.drawable.mb5u32_mb5ucom,
- R.drawable.mb5u33_mb5ucom, R.drawable.mb5u34_mb5ucom,
- R.drawable.mb5u35_mb5ucom, R.drawable.mb5u36_mb5ucom,
- R.drawable.mb5u37_mb5ucom, R.drawable.mb5u38_mb5ucom,
- R.drawable.mb5u39_mb5ucom, R.drawable.mb5u40_mb5ucom,
- R.drawable.mb5u41_mb5ucom, R.drawable.mb5u42_mb5ucom,
- R.drawable.mb5u43_mb5ucom, R.drawable.mb5u44_mb5ucom };
-
- public static ArrayList<Map<String, Object>> getData() {
- ArrayList<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
- for (int i = 0; i < 23; i++) {
- Map<String, Object> map = new HashMap<String, Object>();
- map.put("img", image[i]);
- list.add(map);
- }
- return list;
- }
正式綁定
- public class MyGridViewDemo extends Activity implements OnTouchListener {
-
- private RelativeLayout myRl;
- private GridView myGridView;
- private ArrayList<Map<String, Object>> mArray;
- private MyAdapter adapter;
- private int mDragViewX;
- private int mDragViewY;
-
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
-
- this.requestWindowFeature(Window.FEATURE_NO_TITLE);// 去掉標題欄
- this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
- WindowManager.LayoutParams.FLAG_FULLSCREEN);// 去掉信息欄
-
- setContentView(R.layout.main);
- myRl = (RelativeLayout) findViewById(R.id.ll);
- myGridView = new GridView(this);
- mArray = Utils.getData();
- System.out.println(mArray.size());
- adapter = new MyAdapter(this, myGridView.getId(), mArray);
- myGridView.setAdapter(adapter);
- // GridView的列數
- myGridView.setNumColumns(5);
-
- myRl.addView(myGridView);
-
- myGridView.setOnTouchListener(this);
-
- }
-
- class MyAdapter extends ArrayAdapter<Map<String, Object>> {
-
- public MyAdapter(Context context, int textViewResourceId,
- List<Map<String, Object>> objects) {
- super(context, textViewResourceId, objects);
- }
-
- public ArrayList<Map<String, Object>> getList() {
- return mArray;
- }
-
- public View getView(int position, View convertView, ViewGroup parent) {
- View row = convertView;
- if (row == null) {
- LayoutInflater inflater = getLayoutInflater();
-
- row = (View) inflater.inflate(R.layout.mygrid_item, null);
- }
- ImageView imageView = (ImageView) row.findViewById(R.id.img);
-
- imageView.setImageResource(Integer.valueOf(mArray.get(position)
- .get("img").toString()));
-
- if (from == position) {
- imageView.setVisibility(View.INVISIBLE);
- } else if (View.INVISIBLE == imageView.getVisibility()) {
- imageView.setVisibility(View.VISIBLE);
- }
-
-
- Log.i("ivan", "position =" + position + "aniFrom =" + aniFrom
- + "aniTo" + aniTo);
- Animation ani = null;
- if (position > aniTo && position <= aniFrom) {
- if (position % 5 == 0) {
- ani = new TranslateAnimation(355, 0, -85, 0);
- } else {
- ani = new TranslateAnimation(-60, 0, 0, 0);
- }
- } else if (position < aniTo && position >= aniFrom) {
- if (position % 5 == 4) {
- ani = new TranslateAnimation(-355, 0, 85, 0);
- } else {
- ani = new TranslateAnimation(60, 0, 0, 0);
- }
- }
- if (ani != null) {
- ani.setAnimationListener(new AnimationListener() {
-
- @Override
- public void onAnimationStart(Animation animation) {
- // TODO Auto-generated method stub
- onAnimation = true;
- }
- @Override
- public void onAnimationRepeat(Animation animation) {
- // TODO Auto-generated method stub
- }
- @Override
- public void onAnimationEnd(Animation animation) {
- // TODO Auto-generated method stub
- onAnimation = false;
- }
- });
- ani.setDuration(500);
- imageView.setAnimation(ani);
- }
-
- return imageView;
- }
-
- }
- private boolean onAnimation = false;
- private int from = -1;
- private int to = -1;
- private int aniTo;
- private int aniFrom;
-
- @Override
- public boolean onTouch(View v, MotionEvent event) {
-
- int x = (int) event.getX();
- int y = (int) event.getY();
- int position = myGridView.pointToPosition(x, y);
-
- switch (event.getAction()) {
- case MotionEvent.ACTION_DOWN:
-
- // 如果沒有點擊到圖片直接break
- System.out.println("position =" + position);
- if (position == -1) {
- break;
- }
-
- // 獲取到點擊的View
- View tempView = myGridView.getChildAt(position
- - myGridView.getFirstVisiblePosition());
- System.out.println("tempView =" + tempView);
- if (tempView == null) {
- break;
- }
- // 開啟View的緩存
- tempView.setDrawingCacheEnabled(true);
- // tempView.getTop()獲取到tempView自身的位置,因為按下的時候應該顯示的位置和他自身的位置相同
- // tempView.getLeft() 同理
- startDragging(tempView.getDrawingCache(), tempView.getTop(),
- tempView.getLeft());
-
- // 獲取點擊的位置距所點擊圖片頂部的距離mDragViewX,mDragViewY
- mDragViewX = x - tempView.getLeft();
- mDragViewY = y - tempView.getTop();
-
- from = position;
- tempView.setVisibility(View.INVISIBLE);
- break;
- case MotionEvent.ACTION_MOVE:
- if (myDragView != null) {
-
- RelativeLayout.LayoutParams rllp = (LayoutParams) myDragView
- .getLayoutParams();
- rllp.leftMargin = x - mDragViewX;
- rllp.topMargin = y - mDragViewY;
- myDragView.setLayoutParams(rllp);
- }
- if (position != -1) {
- to = position;
- }
- Log.i("ivan", "form=" + from);
- if (from != to && from != -1 && to != -1 &&!onAnimation) {
-
- aniFrom = from;
- aniTo = to;
- Map<String, Object> temp = adapter.getItem(from);
- adapter.remove(temp);
- adapter.insert(temp, to);
-
- from = to;
-
- }
-
- break;
-
- case MotionEvent.ACTION_UP:
- if (myDragView != null) {
- // 把myDragView 從RelativeLayout中刪除
- myRl.removeView(myDragView);
- }
- // 獲取到松手位置的圖片讓其顯示
- View end = myGridView.getChildAt(from
- - myGridView.getFirstVisiblePosition());
- if (end != null) {
- end.setVisibility(View.VISIBLE);
- }
-
- from = -1;
- to = -1;
- break;
-
- }
-
- return true;
- }
-
- private ImageView myDragView;
-
- private void startDragging(Bitmap tempBitmap, int top, int left) {
-
- ImageView iv = new ImageView(getApplication());
- RelativeLayout.LayoutParams rllp = new RelativeLayout.LayoutParams(-2,
- -2);
-
- rllp.leftMargin = left;
- rllp.topMargin = top;
- iv.setImageBitmap(tempBitmap);
- // 測試方法看iv是否有值 作用是讓此View填充全屏
- // setContentView(iv);
- myDragView = iv;
-
- myRl.addView(myDragView, rllp);
- // 兩種寫法一樣
- // mDragView.setLayoutParams(rllp);
- // rl.addView(mDragView);
-
- }
---------------------------------------------
dragwindow 圖片拖動
- public class DragwindowActivity extends Activity {
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- //setContentView(R.layout.main);
-
- //設置窗體的屬性
- WindowManager.LayoutParams params = new LayoutParams();
- params.height = WindowManager.LayoutParams.FILL_PARENT;
- params.width = WindowManager.LayoutParams.FILL_PARENT;
- params.format = PixelFormat.TRANSLUCENT;
- DisplayMetrics dm = getResources().getDisplayMetrics();
- final int screenWidth = dm.widthPixels;
- final int screenHeight = dm.heightPixels-50; //拖動窗體內的范圍
-
- //把要拖動view布局文件孵化成view
- LayoutInflater inflater = LayoutInflater.from(this);
- View view = inflater.inflate(R.layout.main, null);
- ImageButton button = (ImageButton) view.findViewById(R.id.ib_tt);
- button.setOnTouchListener(new OnTouchListener() {
- int lastX,lastY; //焦點
- @Override
- public boolean onTouch(View v, MotionEvent event) {
- int me = event.getAction();
- Log.i("TAG", "Touch:"+me); //按下是0,拖動是2,彈起是1;
- switch(me){
- case MotionEvent.ACTION_DOWN:
- lastX = (int) event.getRawX();
- lastY = (int) event.getRawY();
- Log.i("TAG", "down x="+lastX+" ,y="+lastY);
- break;
- case MotionEvent.ACTION_MOVE:
- int dx = (int) event.getRawX()-lastX;
- int dy = (int) event.getRawY()-lastY;
- Log.i("TAG", "d x="+dx+" ,d y="+dy); //拖動的坐標
- //拖動移位後的坐標
- int left = v.getLeft() + dx;
- int top = v.getTop() + dy;
- int right = v.getRight() + dx;
- int bottom = v.getBottom() + dy;
- if(left<0){
- left = 0;
- right=left+v.getWidth();
- }
- if(right>screenWidth){
- right=screenWidth;
- left = right-v.getWidth();
- }
- if(top<0){
- top=0;
- bottom = top+v.getHeight();
- }
- if(bottom>screenHeight){
- bottom = screenHeight;
- top = bottom - v.getHeight();
- }
- v.layout(left, top, right, bottom);
- lastX = (int) event.getRawX();
- lastY = (int) event.getRawY();
- break;
- case MotionEvent.ACTION_UP:
- break;
- }
- return false;
- }
- });
- WindowManager manager = (WindowManager) getSystemService(WINDOW_SERVICE);
- manager.addView(view, params);
- }
----------------------讀取相冊--畫圖保存
- ImageView iv1;
- Canvas canvas ;
- Bitmap alteredBitmap;
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- iv1 =(ImageView) findViewById(R.id.iv1);
- iv1.setOnTouchListener(this);
- }
- public void selectImage(View view) {
- Intent intent = new Intent(Intent.ACTION_PICK);
- intent.setType("image/*");
- startActivityForResult(intent, 200);
- }
- public void saveImage(View view){
- try {
- Uri uri = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, new ContentValues());
- OutputStream os = getContentResolver().openOutputStream(uri);
- Boolean result = alteredBitmap.compress(CompressFormat.JPEG, 50, os);
- if(result){
- Toast.makeText(this, "保存成功", 1).show();
- Intent intent = new Intent(Intent.ACTION_MEDIA_MOUNTED,Uri.parse("file://"+Environment.getExternalStorageDirectory()));
- sendBroadcast(intent);
- }else{
- Toast.makeText(this, "保存失敗", 1).show();
- }
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- }
- }
- @Override
- protected void onActivityResult(int requestCode, int resultCode, Intent data) {
- super.onActivityResult(requestCode, resultCode, data);
- if (requestCode == 200) {
- Uri uri = data.getData();
- try {
- // InputStream is =getContentResolver().openInputStream(uri);
- //得到屏幕大小
- Display currentDisplay = getWindowManager().getDefaultDisplay();
- int dw = currentDisplay.getWidth();
- int dh = currentDisplay.getHeight();
-
- System.out.println(dw+"--"+dh);
- BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
- // 如果設置了injustDecodeBounds這個屬性,不會真的解析bitmap,只返回bitmap的寬高和圖片屬性
- bmpFactoryOptions.inJustDecodeBounds = true;
-
- Bitmap bmp = BitmapFactory.decodeFile("/sdcard/066.JPG",
- bmpFactoryOptions); //參數傳入只為得到bmp圖屬性 ,再縮小
- int heightRatio = (int) Math.ceil(bmpFactoryOptions.outHeight
- / (float) dh);
- int widthRatio = (int) Math.ceil(bmpFactoryOptions.outWidth
- / (float) dw);
-
- // 判斷是否要進行縮放
- if (heightRatio > 1 && widthRatio > 1) {
- if (heightRatio > widthRatio) {
- // 高度變化大,按高度縮放
- bmpFactoryOptions.inSampleSize = heightRatio;
- } else {
- // 寬度變化大,按寬度縮放
- bmpFactoryOptions.inSampleSize = widthRatio;
- }
- }
- // 把inJustDecodeBounds設置為false,這樣才會真正的decode這個位圖
- bmpFactoryOptions.inJustDecodeBounds = false;
- //得到新圖片流
- InputStream newis = getContentResolver().openInputStream(uri);
- bmp = BitmapFactory.decodeStream(newis, null, bmpFactoryOptions);
- // 創建一個bitmap的拷貝
- // 創建了一個空的bitmap ,用原來的參數填充
- alteredBitmap = Bitmap.createBitmap(bmp.getWidth(),
- bmp.getHeight(), bmp.getConfig());
- // 創建一個畫布
- canvas = new Canvas(alteredBitmap);
- // 創建一個畫筆
- Paint paint = new Paint();
- Matrix matrix = new Matrix();
- canvas.drawBitmap(bmp, matrix, paint);
- iv1.setImageBitmap(alteredBitmap);
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- }
- }
- }
- float downx = 0;
- float downy = 0;
- float upx = 0;
- float upy = 0;
- @Override
- public boolean onTouch(View v, MotionEvent event) {
- int eventtype = event.getAction();
- Paint paint = new Paint();
- paint.setColor(Color.GREEN);
- paint.setStrokeWidth(5);
- switch (eventtype) {
- case MotionEvent.ACTION_DOWN:
- downx = event.getX();
- downy = event.getY();
- break;
- case MotionEvent.ACTION_MOVE:
- upx = event.getX();
- upy = event.getY();
- canvas.drawLine(downx, downy, upx, upy, paint);
- iv1.invalidate();
- downx = upx;
- downy = upy;
- break;
- case MotionEvent.ACTION_UP:
- upx = event.getX();
- upy = event.getY();
- canvas.drawLine(downx, downy, upx, upy, paint);
- iv1.invalidate();
- break;
- }
- return true;
- }