2014-11-04 93 views
0

我是一个新的学生的Android开发,我试图在屏幕中间画一个矩形,下面是我的源代码,但它赢了在画布上画任何东西,你能帮助解释这可能是什么吗?谢谢。如何在屏幕中间画一个矩形 - 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); 
} 

} 

回答

0

您不能通过创建画布来绘制活动。这必须从视图的onDraw方法完成。

所以,而不是创建从活动画布上,看出你MyDrawView类的onDraw方法之一。

里面的类,你可以使用getMeasuredHeight和getMeasuredWidth得到当前视图的大小并相应地绘制。

不知道您的矩形的目的,但是,如果只是为了装饰的目的,它可能会更快地创建一个可绘制的XML文件,并放入ImageView的在版面的中间。

相关问题