我正在尝试制作一些视图,以允许用户使用绘制的线条连接某些元素。
例如在图像上有几个TextViews
,用户从一条线到另一条线画一条线,如果连接正确(从text1到text3),线将保持不变。
现在,我已经实现了自定义视图,它绘制了一条直线,紧随您的手指:
public class FingerLineView extends View {
private final Paint mPaint;
private float startX;
private float startY;
private float endX;
private float endY;
public FingerLineView(Context context) {
this(context, null);
}
public FingerLineView(Context context, AttributeSet attrs) {
super(context, attrs);
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setStyle(Style.STROKE);
mPaint.setColor(Color.RED);
}
@Override protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawLine(startX, startY, endX, endY, mPaint);
}
@Override
public boolean onTouchEvent(@NonNull MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
startX = event.getX();
startY = event.getY();
// Set the end to prevent initial jump
endX = event.getX();
endY = event.getY();
invalidate();
break;
case MotionEvent.ACTION_MOVE:
endX = event.getX();
endY = event.getY();
invalidate();
break;
case MotionEvent.ACTION_UP:
endX = event.getX();
endY = event.getY();
invalidate();
break;
}
return true;
}
}
它是这样工作的:
但是我不知道如何用TextView
之类的视图元素正确地“连接”它。
我应该使用完全自定义的视图来执行此操作,还是有一些更好的方法来执行此操作?
答案 0 :(得分:1)
画布比您可能知道的还要强大。 ;)
使用其drawText
方法。出色的性能,易于使用,并且100%可定制。
编辑: 这是一个小的示例代码,计算只是虚拟的,您必须将其放置在需要的地方:
public class FingerLineView extends View {
private final Paint mPaint;
private final Paint mPaintText;
private float startX;
private float startY;
private float endX;
private float endY;
public FingerLineView(Context context) {
this(context, null);
}
public FingerLineView(Context context, AttributeSet attrs) {
super(context, attrs);
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setColor(Color.RED);
mPaintText = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaintText.setColor(Color.BLACK);
mPaintText.setTextSize(30);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawLine(startX, startY, endX, endY, mPaint);
canvas.drawText("TEXT", startX - mPaintText.measureText("TEXT")/2, startY - 30, mPaintText);
canvas.drawText("TEXT", endX - mPaintText.measureText("TEXT")/2, endY - 30, mPaintText);
}
@Override
public boolean onTouchEvent(@NonNull MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
startX = event.getX();
startY = event.getY();
// Set the end to prevent initial jump
endX = event.getX();
endY = event.getY();
invalidate();
break;
case MotionEvent.ACTION_MOVE:
endX = event.getX();
endY = event.getY();
invalidate();
break;
case MotionEvent.ACTION_UP:
endX = event.getX();
endY = event.getY();
invalidate();
break;
}
return true;
}
}