我有两个imageView
,我需要在它们之间放一条线,当通过触摸线移动其中一个图像时,必须遵循imageView
(拉伸)。如何将行起点和终点附加到两个不同的imageView
并动态更改行?
这是我的代码:
public class MainActivity extends AppCompatActivity implements View.OnTouchListener {
ImageView mLeftTop;
ImageView mCenterTop;
float dX, dY;
PathView mPathView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mPathView = (PathView)findViewById(R.id.path_view);
mLeftTop = (ImageView)findViewById(R.id.left_top);
mCenterTop = (ImageView)findViewById(R.id.center_top);
mLeftTop.setOnTouchListener(this);
mCenterTop.setOnTouchListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
dX = v.getX() - event.getRawX();
dY = v.getY() - event.getRawY();
break;
case MotionEvent.ACTION_MOVE:
v.animate()
.x(event.getRawX() + dX)
.y(event.getRawY() + dY)
.setDuration(0)
.start();
break;
default:
return false;
}
return true;
}
}
自定义视图:
public class PathView extends View {
private Paint mPaint;
private Path mPath;
public PathView(Context context) {
super(context);
init();
}
public PathView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public PathView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
public PathView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init();
}
private void init() {
mPaint = new Paint();
mPaint.setStyle(Paint.Style.STROKE);
mPath = new Path();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
mPaint.setColor(Color.BLACK);
mPaint.setStrokeWidth(8);
mPath.moveTo(100, 400);
mPath.lineTo(400, 800);
canvas.drawPath(mPath, mPaint);
}
}