2014-11-04 81 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的在版面的中間。

相關問題