如何在屏幕中间绘制一个矩形-Android开发

时间:2014-11-04 00:28:34

标签: android canvas view window-managers

我是android dev的新学生,我正在尝试在屏幕中间绘制一个rect,下面是我的源代码,但它不会在画布上绘制任何东西,你能帮忙解释一下吗?怎么会这样?感谢。

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);
}

}

1 个答案:

答案 0 :(得分:0)

您无法通过创建Canvas来绘制活动。这必须从视图的onDraw方法完成。

因此,不是从活动中创建画布,而是从MyDrawView类中的onDraw方法获取画布。

在类的内部,您可以使用getMeasuredHeight和getMeasuredWidth来获取当前视图的大小并相应地绘制。

不确定矩形的用途,但是,如果仅用于装饰目的,创建可绘制的xml文件并在布局中间放入ImageView可能会更快。