No padding-effect in custom ImageView

559 Views Asked by At

I've got an issue assigning padding-values to my custom ImageView. Please note, that I'm not extending ImageView but View:

public class CustomImageView extends View

The image is loaded from the assets folder via path. Source- and Target-Rect are calculated in onLayout(...) and the bitmap is assigned in onDraw(...).

Good news: The Image is displayed ;-)

Bad News: Assigning padding-values by setPadding(...) has no effect on the image (problem to solve!). I tested this with a "normal" ImageView-Object and it worked like desired. But unfortunately the task is to extend my custom class from View, not ImageView. So if anybody knows how to solve this - and I'm definitely not the first one with this problem ;-) - let me know!

Here's the onDraw-Method, no magic:

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    if (bitmap != null)
        canvas.drawBitmap(bitmap, sourceRect, targetRect, paint);
}
1

There are 1 best solutions below

0
On BEST ANSWER

When you are setting paddings to view, they should be considered during the drawing. You can achieve this, by creating a BitmapDrawable variable in your custom view, and then initialize it and draw according to padding, for example.

private BitmapDrawable mDrawable;

public void setBitmap(Bitmap bitmap) {
    mDrawable = new BitmapDrawable(getResources(), bitmap);
    invalidate();
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    if (mDrawable != null) {
        int paddingLeft = getPaddingLeft();
        int paddingTop = getPaddingTop();
        int paddingRight = getPaddingRight();
        int paddingBottom = getPaddingBottom();

        int contentWidth = getWidth() - paddingLeft - paddingRight;
        int contentHeight = getHeight() - paddingTop - paddingBottom;

        mDrawable.setBounds(paddingLeft, paddingTop,
                paddingLeft + contentWidth, paddingTop + contentHeight);
        mDrawable.draw(canvas);
    }
}