Android:调整customview的高度

时间:2016-12-03 06:01:49

标签: android layout android-imageview android-custom-view

我已经创建了一个圆形自定义视图,如screenShot所示。您可以看到圆形的下半部分在布局中切片。如何调整其高度。 这是相关代码

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

1 个答案:

答案 0 :(得分: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>

但由于屏幕尺寸不同, android:layout_width =&#34; wrap_content&#34; 仍然存在问题。然后,您将获得屏幕宽度并相应地设置高度。