我如何绘制我的自定义视图,它可以通过使用这个库变得可缩放
package com.example.mindmapping;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import com.otaliastudios.zoom.ZoomLayout;
public class MainActivity extends AppCompatActivity {
<strong i="7">@Override</strong>
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MindMap map = new MindMap(this);
setContentView(R.layout.activity_main);
ZoomLayout zoomLayout = findViewById(R.id.zoomLayoutContainer);
zoomLayout.addView(map);
setContentView(map);
}
}
其中 map 是自定义视图,扩展 View 和覆盖 onDraw 方法,它包含其他元素,如 TextElement 和其他也是自定义视图或从线性布局扩展并包含文本视图:像这样
package com.example.mindmapping;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.View;
import android.widget.Toast;
public class MindMap extends View {
private Context context;
private Canvas canvas;
private Paint brush;
//Canvas Variables
private float centerMarginX;
private float centerMarginY;
private float mWidth;
private float mHeight;
public MindMap(Context context) {
super(context);
this.context = context;
initSetup();
}
<strong i="11">@Override</strong>
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
this.canvas = canvas;
initDrawing();
}
public void initSetup() {
brush = new Paint(Paint.ANTI_ALIAS_FLAG);
}
public void initDrawing() {
brush.setStyle(Paint.Style.STROKE);
brush.setStrokeWidth(10);
brush.setColor(Color.parseColor("black"));
canvas.drawText("Helo ",50,50,brush);
mWidth = getMeasuredWidth();
mHeight = getMeasuredHeight();
centerMarginX = mWidth / 2;
centerMarginY = mHeight / 2;
TextElement textElement = new TextElement(context, "Main Topic");
textElement.setX(centerMarginX - (textElement.getLayoutWidth() / 2));
textElement.setY(centerMarginY - (textElement.getLayoutHeight() / 2));
textElement.draw(canvas);
TextElement textElement1 = new TextElement(context, "Another One");
textElement1.setX(textElement.getX() + textElement.getLayoutWidth() + 600);
textElement1.setY(textElement.getY() - textElement.getLayoutHeight());
textElement1.draw(canvas);
Toast.makeText(this.context,"Drawn",Toast.LENGTH_SHORT).show();
}
}
即使调用了 onDraw 方法,也不会在 ZoomLayout 中绘制自定义视图(在这种情况下为地图),但是当我在 setContentView 而不是布局文件中设置地图并且不使用 ZoomLayout 时,地图绘制在画布上,我想要绘制我的自定义视图,该视图应该可以使用此库进行缩放
1.8.0
在画布上没有绘制任何内容,甚至没有在 initDrawing() 中绘制的 helo 文本
再次调用 setContentView 将地图设置为视图作为测试,这是一个注释,删除它并不能解决问题
您的自定义视图可能以 0 大小绘制。 尝试使用设备/模拟器上的开发人员设置或通过 Android Studio 的布局检查器调试您的布局。
谢谢 !
我需要在覆盖的 onMeasure 中调用 setMeasuredDimension,因为这是一个完全自定义的视图,文档!
我的问题已经解决了。
最有用的评论
谢谢 !
我需要在覆盖的 onMeasure 中调用 setMeasuredDimension,因为这是一个完全自定义的视图,文档!
我的问题已经解决了。