2017-05-03 3 views
0

J'essaie de créer une vue qui remplira tout l'espace disponible sur l'écran. Iv'e définir les paramètres de ma disposition à match_parent et utilisé getHeight() et getWidth() lorsqu'il a dessiné Rect sur Canvas et il est encore remplir seulement environ deux tiers de l'écran.CustomView ne remplit pas l'espace disponible

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

Répondre

3

Vous avez inversé la largeur et la hauteur de cette ligne:

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

Paramètres de drawRect() procédé sont comme suit:

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

Vous avez utilisé canvas.getHeight() comme right et canvas.getWidth() comme bottom, c'est pourquoi le height de custom view est la même que dispositif width.

SOLUTION:

Vous devez utiliser canvas.getWidth() comme right et canvas.getHeight() comme bottom

méthode de mise à jour onDraw() comme ci-dessous:

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

Espérons que cela aidera ~