Bitmap和canvas的应用

画虚线
 

 

 

  
SET_WALLPAPER
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;
	}



 

转载于:https://my.oschina.net/u/175434/blog/699976

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值