我无法在imagview上划一条线。以下是我的代码。
public class MainActivity extends Activity implements OnTouchListener {
private Paint mPaint;
private ImageView img;
private Bitmap newBitmap;
float downx = 0;
float downy = 0;
float upx = 0;
float upy = 0;
private Canvas newCanvas;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
img = (ImageView)findViewById(R.id.imageView1);
img.setOnTouchListener(this);
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setDither(true);
mPaint.setColor(0xFFFF0000);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(12);
Bitmap bitmap = ((BitmapDrawable)img.getDrawable()).getBitmap();
Config config = bitmap.getConfig();
if(config == null){
config = Bitmap.Config.ARGB_8888;
}
newBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), config);
newCanvas = new Canvas(newBitmap);
newCanvas.drawBitmap(bitmap, 0, 0,mPaint);
img.setImageBitmap(newBitmap);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
downx = event.getX();
downy = event.getY();
break;
case MotionEvent.ACTION_MOVE:
upx = event.getX();
upy = event.getY();
// newCanvas.drawLine(downx, downy, upx, upy, mPaint);
img.invalidate();
downx = upx;
downy = upy;
break;
case MotionEvent.ACTION_UP:
upx = event.getX();
upy = event.getY();
newCanvas.drawLine(downx, downy, upx, upy, mPaint);
img.invalidate();
break;
case MotionEvent.ACTION_CANCEL:
break;
default:
break;
}
return true;
}
}
请帮助我解决这个问题。谢谢。