我正在使用这段代码让用户用手指绘制o线:
public class DrawingView extends View {
private Paint paint;
private Path path;
public DrawingView(Context context , AttributeSet attrs) {
super(context, attrs);
this.paint = new Paint();
this.paint.setAntiAlias(true);
this.paint.setColor(Color.BLACK);
this.paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStrokeWidth(5f);
this.path = new Path();
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawPath(path, paint);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
float eventX = event.getX();
float eventY = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
path.moveTo(eventX, eventY);
return true;
case MotionEvent.ACTION_MOVE:
case MotionEvent.ACTION_UP:
path.lineTo(eventX, eventY);
break;
default:
return false;
}
// Schedules a repaint.
invalidate();
return true;
}
public void clear() {
path.reset();
invalidate();
}
public void setPaintColor(int color) {
paint.setColor(color);
}
public int getCurrentPaintColor() {
return paint.getColor();
}
}
使用方法setPaintColor()我正在改变颜色的颜色。但是当我改变颜色时,整个绘图都会改变(甚至是我之前画过的线条)。如何更改颜料的颜色并保留以前的图纸?我尝试创建新路径,但之前的绘图消失了。
答案 0 :(得分:2)
你需要为此创建一个小的数据结构,它将存储图形的颜色和路径。这是一个例子:
class PaintClass
{
Path path;
int Color;
public int getColor() { return color; }
public void setColor(int color){this.Color = color;}
public int getPath() { return path; }
public void setPath(Path path){this.path = path;}
...
...
...
}
现在维护一个具有PaintClass对象的arraylist。
在onDraw方法
中实现它{
for(PaintClass item : yourArrayListOfPaintClassObjects)
{
//set Paint color like this
setPaintColor(item.getPaintColor());
canvas.drawPath(.....,paint);
}
}
注意:在每个新绘图中,在arraylist中添加newely make PaintClass对象...
答案 1 :(得分:2)
您需要使用此代码才能帮助您画线
public class MainActivity extends Activity implements OnTouchListener {
private float x;
private float y;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyCustomPanel view = new MyCustomPanel(this);
ViewGroup.LayoutParams params =
new ViewGroup.LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT);
addContentView(view, params);
view.setOnTouchListener(this);
}
private class MyCustomPanel extends View {
public MyCustomPanel(Context context) {
super(context);
}
@Override
public void draw(Canvas canvas) {
Paint paint = new Paint();
paint.setColor(Color.GREEN);
paint.setStrokeWidth(6);
canvas.drawLine(10,10,50,50,paint);
paint.setColor(Color.RED);
canvas.drawLine(50, 50, 90, 10, paint);
canvas.drawCircle(50, 50, 3, paint);
canvas.drawCircle(x,y,3,paint);
}
}
public boolean onTouch(View v, MotionEvent event) {
x = event.getX();
y = event.getY();
v.invalidate();
return true;
}
}
答案 2 :(得分:1)
你需要使用你的逻辑来保存颜色并在onDraw()方法中加载它们,因为有时候我创建了具有positionX,positionY,颜色属性的对象Point。:)