public class MainActivity extends Activity implements OnTouchListener { private int x;//绘画开始的横坐标 private int y;//绘画开始的纵坐标 private int width = 180;//绘画的宽度 private int height = 40;//绘画的高度 private Bitmap bitmap;//生成的位图 // private MyView myView;//绘画选择区域 private ImageView image1; private ImageView image2; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); image1 = (ImageView) findViewById(R.id.image1); image2 = (ImageView) findViewById(R.id.image2); image1.setOnTouchListener(this); } @Override public boolean onTouch(View v, MotionEvent event) { try { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: { x = (int) event.getX(); y = (int) event.getY(); moveViewWithFinger(image2,x,y); image2.setVisibility(View.VISIBLE); image2.setImageBitmap(getBitmap(this)); break; } case MotionEvent.ACTION_MOVE: { x = (int) event.getX(); y = (int) event.getY(); image2.setImageBitmap(getBitmap(this)); moveViewWithFinger(image2,x,y); break; } case MotionEvent.ACTION_UP: { image2.setImageBitmap(null); image2.setVisibility(View.GONE); break; } default: { image2.setImageBitmap(null); image2.setVisibility(View.GONE); break; } } }catch (Exception e){ e.getStackTrace(); } return true; } private void moveViewWithFinger(View view, float rawX, float rawY) { RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) view .getLayoutParams(); params.leftMargin = (int) rawX-250; params.topMargin = (int) rawY - 250; view.setLayoutParams(params); } private Bitmap getBitmap(Activity activity) { View view = activity.getWindow().getDecorView(); view.setDrawingCacheEnabled(true); view.buildDrawingCache(); bitmap = view.getDrawingCache(); bitmap = Bitmap.createBitmap(bitmap, x, y, width, height); view.setDrawingCacheEnabled(false); return bitmap; } }
/// main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent"> <ImageView android:id="@+id/image1" android:layout_width="fill_parent" android:layout_height="fill_parent" android:src="@drawable/test" /> <ImageView android:id="@+id/image2" android:layout_width="180dp" android:layout_height="45dp" android:visibility="gone" /> </RelativeLayout>源码 : http://download.csdn.net/detail/icesoul1127/9638232