Search code examples
androidcomponentsfill

Fill custom component with image in Android


I created a custom component in Android. I want the background of the custom component to be an image that fills the component and re-sizes as the component does.

At the moment I can draw the images but I am struggling to make it fill the component.

I draw my component as follow:

// Called from Constructor
private void initBrushes() {
    backgroundPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    backgroundPaint.setStyle(Paint.Style.FILL);
    backgroundPaint.setFilterBitmap(true);
    backgroundBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.background_original);        
}

protected void onDraw(Canvas canvas) {
    canvas.drawBitmap(backgroundBitmap, 0, 0, backgroundPaint);    
}

Solution

  • Just make the image the background of your CustomComponent.

    This can be made trough the xml layout. This would look like:

    <com.mypackage.CustomComponent android:background="@drawable/background_original" />
    

    And at runtime:

    myCustomComponentObject.setBackgroundResource(R.drawable.background_original);