在活动布局内用手指画画?

时间:2017-02-20 16:58:11

标签: java android drawing paint

我的活动:

 public class myMainActivity extends AppCompatActivity {
     @Override
     protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.MyLayout);

     }
 }

我想用手指画出我的布局背景,如下:

enter image description here

1 个答案:

答案 0 :(得分:0)

你需要先拥有一个颜料类

paint = new Paint();
paint.setColor(Color.BLACK);
paint.setStrokeWidth(5);
paint.setStyle(Paint.Style.STROKE);
paint.setPathEffect(new DashPathEffect(new float[]{15.0f, 15.0f}, 0));

并实现以下onTouchListener

public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();

switch (action) {
  case MotionEvent.ACTION_DOWN:


  downx = event.getX();
  downy = event.getY();
  clipPath = new Path();
  clipPath.moveTo(downx, downy);
  tdownx = downx;
  tdowny = downy;
  smallx = downx;
  smally = downy;
  largex = downx;
  largey = downy;
  lastTouchDown = System.currentTimeMillis();
   break;

  case MotionEvent.ACTION_MOVE: 
  upx = event.getX();
  upy = event.getY();
 cropModelArrayList.add(new CropModel(upx, upy));
 clipPath = new Path();
 clipPath.moveTo(tdownx,tdowny);
  for(int i = 0; i<cropModelArrayList.size();i++){ clipPath.lineTo(cropModelArrayList.get(i).getY(),cropModelArrayList.get(i).getX(   ));
    }
   canvas.drawPath(clipPath, paint);
   im_crop_image_view.invalidate();
   downx = upx;
   downy = upy;
   break;
   case MotionEvent.ACTION_UP:
if (System.currentTimeMillis() - lastTouchDown < CLICK_ACTION_THRESHHOLD) {

 cropModelArrayList.clear();
 initcanvas();

 int cx = (screen_width - bmp.getWidth()) >> 1;
 int cy = (screen_height - bmp.getHeight()) >> 1;
 canvas.drawBitmap(bmp, cx, cy, null);
 im_crop_image_view.setImageBitmap(alteredBitmap);

 } else {
 if (upx != upy) {
 upx = event.getX();
 upy = event.getY();


 canvas.drawLine(downx, downy, upx, upy, paint);
clipPath.lineTo(upx, upy);
yourview.invalidate();

   }

  }
  break;
  return true;
   }

您可以找到完整的实施here(ignore the crop method)