2017-05-03 72 views
0

我試圖創建一個視圖,將填充屏幕上的所有可用空間。如果將我的視圖的佈局參數設置爲match_parent,並且在Canvas上繪製Rect時使用了getHeight()getWidth(),並且它仍然只填充屏幕的大約三分之二。CustomView不填充可用空間

<?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> 

CustomView:

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); 
} 

It doesn't fill the whole layout, I want it to fill the white area

回答

3

您已反轉在該線的寬度和高度:

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

drawRect()方法的參數如下:

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

您已經使用canvas.getHeight()rightcanvas.getWidth()作爲bottom,這就是爲什麼custom viewheight是一樣的設備width

SOLUTION:

你應該使用canvas.getWidth()rightcanvas.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); 
} 

希望這將有助於〜