Reputation: 1122
I'm trying to create a view that will fill all the available space on the screen. Iv'e set my view's layout params to match_parent
and used getHeight()
and getWidth()
when drew Rect
on Canvas
and it is still filling only about two thirds of the screen.
<?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);
}
Upvotes: 0
Views: 51
Reputation: 21736
Parameters of drawRect()
method are as below:
drawRect(float left, float top, float right, float bottom, Paint paint)
You have used canvas.getHeight()
as right
and canvas.getWidth()
as bottom
, that's why the height
of custom view
is same as device width
.
SOLUTION:
You should use canvas.getWidth()
as right
and canvas.getHeight()
as bottom
Update onDraw()
method as below:
@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);
}
Hope this will help~
Upvotes: 1
Reputation: 9263
You have inversed the width and height in this line :
canvas.drawRect(0,0, canvas.getWidth(),canvas.getHeight(), paintBackground);
Upvotes: 3