CustomView 未填充可用 space

CustomView doesn't fill available space

我正在尝试创建一个将填充屏幕上所有可用 space 的视图。我将视图的布局参数设置为 match_parent 并在 Canvas 上绘制 Rect 时使用了 getHeight()getWidth() 并且它仍然只填充了大约三分之二屏幕。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:layout_width="match_parent"
xmlns:beat_box="http://schemas.android.com/tools">

<com.yotam.aprivate.demo.mybeatbox.Views.BeatBox
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    beat_box:my_color="5D32EA">
</com.yotam.aprivate.demo.mybeatbox.Views.BeatBox>
</RelativeLayout>

自定义视图:

public class BeatBox extends View {
private int color;
private Context context;
private Paint paintBox = new Paint();
private Paint paintBackground = new Paint();

public BeatBox(Context context, @Nullable AttributeSet attrs) {
    super(context, attrs);
    this.context = context;
    color = getAttrColor(attrs);
    initDrawing();
}
@Override
protected void onDraw(Canvas canvas) {
    canvas.drawRect(0,0,canvas.getHeight(), canvas.getWidth(), paintBackground); //this.getHeight() this.getWidth() also doesn't work
    paintBackground.setShader(new LinearGradient(0, 0, getWidth() , getHeight(), Color.parseColor("#cb356b"), Color.parseColor("#bd3f32"), Shader.TileMode.MIRROR));
    super.onDraw(canvas);
}

你在这一行中颠倒了宽度和高度:

canvas.drawRect(0,0, canvas.getWidth(),canvas.getHeight(), paintBackground); 

drawRect()方法参数如下:

drawRect(float left, float top, float right, float bottom, Paint paint)

您将canvas.getHeight()用作right,将canvas.getWidth()用作bottom,这就是为什么custom viewheight与设备相同width

解决方案:

您应该将 canvas.getWidth() 用作 right,将 canvas.getHeight() 用作 bottom

更新 onDraw() 方法如下:

@Override
protected void onDraw(Canvas canvas) {
    canvas.drawRect(0, 0, canvas.getWidth(), canvas.getHeight(), paintBackground); 
    paintBackground.setShader(new LinearGradient(0, 0, getWidth() , getHeight(), Color.parseColor("#cb356b"), Color.parseColor("#bd3f32"), Shader.TileMode.MIRROR));

    super.onDraw(canvas);
}

希望对你有所帮助~