[英]How to draw a rect in the middle of screen-Android development
我是android开发的新学生,我正在尝试在屏幕中间绘制一个矩形,下面是我的源代码,但是它不会在画布上绘制任何内容,您能帮忙解释一下是? 谢谢。
public class CustomView extends Activity
{
private static final String TAG="CustomeView";
MyDrawView myDrawView;
//RulerView myRulerView;
Canvas canvas=new Canvas();
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.i(TAG, "Get Window manager");
WindowManager windowManager = getWindowManager();
Display display = windowManager.getDefaultDisplay();
DisplayMetrics metrics = new DisplayMetrics();
display.getMetrics(metrics);
//MyDrawView myDrawView=new MyDrawView(this);
myDrawView=(MyDrawView)findViewById(R.id.myDrawView);
myDrawView.screenX=metrics.widthPixels;
myDrawView.screenY=metrics.heightPixels;
Log.i(TAG, "myDrawView.screenX="+ myDrawView.screenX);
Log.i(TAG, "myDrawView.screenY="+ myDrawView.screenY);
//Draw Rect in the middle of screen
Log.i(TAG, "DrawRect");
myDrawView.drawRect(canvas);
}
}
public class MyDrawView extends View {
public float screenX;
public float screenY;
Rect r = new Rect((int)(screenX/2-50),(int)(screenY/2-50),(int)(screenX/2+50),(int)(screenY/2+50));
Paint paint = new Paint();
{
paint.setAntiAlias(true);
paint.setColor(Color.RED);
paint.setStyle(Style.STROKE);
paint.setStrokeWidth(2.5f);
paint.setAlpha(100);
};
public MyDrawView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
public MyDrawView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
public MyDrawView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
// TODO Auto-generated constructor stub
}
public void drawRect(Canvas canvas){
// Draw Rect
canvas.drawRect(r, paint);
}
}
您不能仅通过创建画布来绘制活动。 这必须从视图的onDraw方法完成。
因此,与其从活动中创建画布,不如从MyDrawView类的onDraw方法中获取画布。
在类内部,您可以使用getMeasuredHeight和getMeasuredWidth获取当前视图的大小并进行相应绘制。
不确定矩形的用途,但是,如果仅出于装饰目的,创建一个可绘制的xml文件并将其放入布局中间的ImageView可能会更快。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.