如何在已绘制的视图中添加一行?
我尝试从draw方法中抓取画布并使用它绘制,但它似乎没有用。
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
mCanvas = canvas;
//drawing code here
}
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
Paint paint = new Paint();
paint.setColor(Color.BLACK);
paint.setStrokeWidth(10);
paint.setStyle(Style.FILL);
mCanvas.drawLine(0, 0, 50, 50, paint);
}
}
}
答案 0 :(得分:1)
执行以下步骤:
ACTION_DOWN
时将其设置为true。invalidate()
来电onDraw()
中绘制你的行修改强>
您需要了解绘图过程,以了解保存canvas对象的原因无效。 Android使用两个翻转的缓冲区(命名为缓冲区A和B)。您总是在不可见的缓冲区上绘制。完成绘制后,将切换缓冲区,您将看到绘制的内容。基本上画布将被锁定(以防止在后缓冲区上绘制时翻转),并且此画布对象将被提供给请求重绘的每个视图。之后,画布将被解锁,触发缓冲区被切换。在那一刻,这个画布对象可能仍然在那里,但你在其上做的每一个绘图都将永远不会显示。
可以找到更多信息答案 1 :(得分:1)
您尝试做的最好是使用Drawable。基本上,drawable是一个对象,它封装了可以更新和轻松重用的绘图信息。即
public class LineDrawable extends Drawable {
private int mStartX;
private int mStartY;
private int mEndX;
private int mEndY;
private final Paint mPaint;
public LineDrawable() {
mPaint = new Paint();
mPaint.setColor(Color.RED);
}
public void setLineCoordinates(final int startX, final int startY,
final int endX, final int endY) {
mStartX = startX;
mStartY = startY;
mEndX = endX;
mEndY = endY;
}
public void setColor(final int color){
mPaint.setColor(color);
}
@Override
public void setColorFilter(final ColorFilter colorFilter) {
mPaint.setColorFilter(colorFilter);
}
@Override
public void setAlpha(final int alpha) {
mPaint.setAlpha(alpha);
}
@Override
public void draw(final Canvas canvas) {
canvas.drawLine(mStartX, mStartY, mEndX, mEndY, mPaint);
}
@Override
public int getOpacity() {
return PixelFormat.OPAQUE;
}
public void setSize(final int size){
mPaint.setStrokeWidth(size);
}
}
public class YourView extends View{
private LineDrawable mLineDrawable;
public YourView(final Context context){
mLineDrawable = new LineDrawable();
}
.......
@Override
protected void onDraw(final Canvas canvas){
super.onDraw(canvas);
mLineDrawable.draw(canvas);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
mLineDrawable.setColor(Color.BLUE);
mLineDrawable.setLineCoordinates(0, 0, event.getX(), event.getY());
}
}
}
}
很抱歉这种糟糕的格式,粘贴它似乎搞砸了。