我正在从另一个活动中读取一系列点并从点创建路径。我有一个名为“DrawCanvas”的自定义视图,它扩展了View。目前代码正在投影一个空白的白色画布。有人可以帮我理解为什么画布没有绘制路径吗?
PreviewActivity.java
public class Preview extends Activity{
Canvas newCanvas = new Canvas();
MyPointsList object;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
getIntentData();
Path path = new Path();
if(object.getArrayList().get(0) != null){
for(int i = 0; i < object.getArrayList().size(); i++){
path.moveTo(object.getMyPoint(i).getX(), object.getMyPoint(i).getY());
path.lineTo(object.getMyPoint(i).getX(), object.getMyPoint(i).getY());
}
}
FrameLayout canvas1 = new FrameLayout(this);
DrawCanvas view;
view = new DrawCanvas(Preview.this);
view.onDraw(newCanvas, path);
canvas1.addView(view);
setContentView(canvas1);
}
public void getIntentData(){
Intent i = this.getIntent();
if(i.hasExtra("parcel")){
Bundle b = getIntent().getExtras();
object = b.getParcelable("parcel");
if(object != null){
Log.d("Debug", object.getArrayList().get(5).getX() + " " + object.getArrayList().get(5).getY());
}
else if(object == null){
Log.d("Debug", "Object is equal to Null");
}
}
}
DrawCanvas.java
public class DrawCanvas extends View {
public DrawCanvas(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
public void onDraw(Canvas canvas, Path path){
super.onDraw(canvas);
canvas.drawARGB(255,255,255,255);
Paint black = new Paint();
black.setColor(Color.BLACK);
black.setStyle(Paint.Style.STROKE);
black.setStrokeJoin(Paint.Join.ROUND);
black.setStrokeCap(Paint.Cap.ROUND);
black.setStrokeWidth(3);
canvas.drawPath(path, black);
}
}
答案 0 :(得分:1)
您不会在自定义视图中覆盖正确的onDraw(Canvas canvas)
方法。在我看来,你传递给超级onDraw
一个空画布。然后,您要添加路径,但不要使视图无效以便绘制您的修改
而且,在阻止您的结果显示的其他因素中,您在调用DrawView
后添加了onDraw
。我猜,该视图将“重置”其生命周期(onMeasure
- &gt; onLayout
- &gt; onDraw
...),但其基础知识初始化。 (我不确定那个)。因此,您的所有修改都不会被存储
此外,在绘制内容时不应分配新对象。每次视图无效时,这将占用大量内存。
因此,尝试在start:
初始化Paint
对象
private Paint paint;
private Path path;
public DrawCanvas(Context c) {
super(c);
init();
}
public DrawCanvas(Context c, AttributesSet a) {
super(c, a);
init();
}
private void init() {
// create your paint object
paint = new Paint();
paint.setColor(Color.BLACK);
...
}
关注您的Path
初始化:
public void setPath(Path path) {
// store your new path
this.path = path;
// invalidate the view to call onDraw()
invalidate();
}
最后,覆盖真正的onDraw
方法并绘制逻辑:
@Override
public void onDraw(Canvas canvas) {
if (paint == null || path == null)
return;
canvas.drawPath(path, paint);
}
现在,您可以在Path
中设置新的onCreate()
,如下所示:
setContentView(canvas1);
DrawCanvas draw = new DrawCanvas(this);
canvas1.addView(draw);
draw.setPath(path);
如果您将“重度”处理作为Path对象,则应考虑调用postInvalidate()
,因为invalidate()
将在主线程中调用。