【问题标题】:Android:adjust height of customviewAndroid:调整自定义视图的高度
【发布时间】:2017-04-18 02:33:01
【问题描述】:

我创建了一个圆形自定义视图,如 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" />

截图

【问题讨论】:

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


    【解决方案1】:

    您可以尝试将 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="wrap_content" 仍然存在问题,因为屏幕尺寸不同。然后,您将获得屏幕宽度并相应地设置高度。

    【讨论】:

      猜你喜欢
      • 2012-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多