2016-12-03 154 views
0

我已經創建了一個圓形customview,如screenShot所示。您可以看到圓的下半部分在佈局中切片。如何調整其高度。 下面是相關代碼Android:調整customview的高度

CustomView.class

protected void onDraw(Canvas canvas) { 
    super.onDraw(canvas); 

    float width = (float)getWidth(); 
    float height = (float)getHeight(); 
    float radius; 
    if (width > height){ 
     radius = height/2; 
    }else{ 
     radius = width/2; 
    } 

    Path path = new Path(); 
    path.addCircle(width/2, height/2, radius,Path.Direction.CW); 

    Paint paint = new Paint(); 
    //change color of arc 
    paint.setColor(Color.parseColor("#d50000")); 
    paint.setStrokeWidth(5); 
    paint.setFlags(Paint.ANTI_ALIAS_FLAG); 
    paint.setStyle(Paint.Style.FILL); 

    float center_x, center_y; 
    final RectF oval = new RectF(); 

    paint.setStyle(Paint.Style.STROKE); 
    center_x = width/2; 
    center_y = height/2; 

    oval.set(center_x - radius,center_y - radius,center_x + radius,center_y + radius); 
    canvas.drawArc(oval, 270, 270, false, paint); 
} 

layout.xml

<com.gosemathraj.CustomSemicircleUp 
    android:layout_height="@dimen/semicircle" // 86dp 
    android:layout_width="wrap_content" /> 

截圖

enter image description here

回答

0

您可以嘗試包裹CustomSemicircleUp一個的LinearLayout(或任何佈局),然後中心的圓圖,所以縱橫比保持爲原來的視圖內:

<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent"> 

    <com.gosemathraj.CustomSemicircleUp 
     android:layout_gravity="center" 
     android:layout_height="@dimen/semicircle" // 86dp 
     android:layout_width="wrap_content" /> 

</LinearLayout> 

機器人:layout_width =「WRAP_CONTENT」仍然是有問題的,因爲不同的屏幕尺寸。您將獲得屏幕寬度並相應地設置高度。