Android拖动图片及多层图片叠加
移动前:
移动后:
代码:
1 // 两个用来叠加的图片 2 ImageView mIv; 3 ImageView mIv2; 4 // 显示绘制后的图像 5 ImageView mImageView; 6 Canvas canvas; 7 8 int lastX, lastY;
1 @Override 2 protected void onCreate(Bundle savedInstanceState) { 3 super.onCreate(savedInstanceState); 4 setContentView(R.layout.main); 5 6 mImageView = (ImageView) findViewById(R.id.conta); 7 mImageView.setImageResource(R.drawable.a); 8 mImageView.setDrawingCacheEnabled(true);// 启用缓存 9 10 mIv2 = (ImageView) findViewById(R.id.img2); 11 mIv2.setDrawingCacheEnabled(true); 12 mIv2.setOnTouchListener(this); 13 14 mIv = (ImageView) findViewById(R.id.img); 15 mIv.setDrawingCacheEnabled(true); 16 mIv.setOnTouchListener(this); 17 }
以下是移动的关键代码
1 @Override 2 public boolean onTouch(View v, MotionEvent event) { 3 4 switch (event.getAction()) { 5 6 case MotionEvent.ACTION_DOWN: 7 lastX = (int) event.getRawX(); 8 lastY = (int) event.getRawY(); 9 10 break; 11 case MotionEvent.ACTION_MOVE: 12 13 int dx = (int) event.getRawX() - lastX; 14 int dy = (int) event.getRawY() - lastY; 15 16 int left = v.getLeft() + dx; 17 int top = v.getTop() + dy; 18 int right = v.getRight() + dx; 19 int bottom = v.getBottom() + dy; 20 21 22 Log.i("life", " left = " + left + " v.getLeft=" + v.getLeft() + " ; event.getRawX = "
+ event.getRawX() + " ; lastX = " + lastX + " dx = " + dx); 26 27 v.layout(left, top, right, bottom); 28 29 lastX = (int) event.getRawX(); 30 lastY = (int) event.getRawY(); 31 32 break; 33 case MotionEvent.ACTION_UP: 34 35 break; 36 } 37 38 return true; 39 }
save按钮的事件处理
1 @SuppressLint("NewApi") 2 public void save(View view) { 3 // 保存叠加的图片 4 Bitmap bitmap = mImageView.getDrawingCache(); 5 if (canvas == null) { 6 canvas = new Canvas(bitmap); 7 } 8 // 根据两个机器人的位置绘制 9 canvas.drawBitmap(mIv.getDrawingCache(), mIv.getLeft(),mIv.getTop(), null); 10 canvas.drawBitmap(mIv2.getDrawingCache(), mIv2.getLeft(),mIv2.getTop(), null); 11 12 // 显示在界面上 13 mImageView.setImageBitmap(bitmap); 14 15 // 保存至本地 16 File f = new File(getCacheDir().getAbsolutePath() + "/" 17 + SystemClock.currentThreadTimeMillis() + "img.jpg"); 18 try { 19 saveMyBitmap(f, bitmap); 20 } catch (IOException e) { 21 e.printStackTrace(); 22 } 23 24 // 将两个机器人设置不可见 25 mIv.setVisibility(View.GONE); 26 mIv2.setVisibility(View.GONE); 27 }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。