Put a clamp on it


I wanted to have a background that is horizontally centered, and clamp the pixels on the left and right side. It seems as though clamping is only for pixels to the right and bottom of an image. This called for some image handling to get the missing clamp.

Oversimplified steps
1)Create a mirror of the image
2)Create a clamp of result from step 1(This is our left clamp)
3)Draw clamp from step 2
4)Draw original image
5)generate clamp for original image(this will be our right side)
6)Draw image from step 5

Here is a picture showing the final result at the top with the clamps and image displayed below.
Clamp Images

Here are the key steps:

Step 1
public Bitmap mirrorImage(Bitmap aBitmap){
float[] lMirrorY =
{ -1, 0, 0,
0, 1, 0,
0, 0, 1
};
Matrix lMatrixMirrorY = new Matrix();
lMatrixMirrorY.setValues(lMirrorY);
Bitmap lMirrorBitmap = Bitmap.createBitmap(aBitmap, 0, 0, aBitmap.getWidth(), aBitmap.getHeight(), lMatrixMirrorY, true);

return lMirrorBitmap;
}

Steps 2 and 5
public Bitmap drawClamp(Bitmap aBitmap){
int lMiddle = (mIntendedRect.right - aBitmap.getWidth())/2;
int lHeight = aBitmap.getHeight();

Bitmap lBitmap = Bitmap.createBitmap(
lMiddle,
lHeight,
Bitmap.Config.ARGB_8888);
Canvas lCanvas = new Canvas(lBitmap);
Shader lShader = new BitmapShader(aBitmap,
Shader.TileMode.CLAMP,
Shader.TileMode.CLAMP);
Paint lNewPaint = new Paint();
lNewPaint.setShader(lShader);
Rect lRect= new Rect(aBitmap.getWidth(),0, mIntendedRect.right/2+aBitmap.getWidth(), aBitmap.getHeight());
lCanvas.translate(-aBitmap.getWidth(), 0);
lCanvas.drawRect(lRect, lNewPaint);
return lBitmap;
}

to get the left side of the clamp:
public Bitmap drawLeftClamp(Bitmap aBitmap){
Bitmap lMirror = mirrorImage(aBitmap);
return drawClamp(lMirror);
}

The rest is just calculating where to place the images:
Bitmap lLeftClamp = drawLeftClamp(this.getBitmap());
canvas.drawBitmap(lLeftClamp, 0, 0, lPaint);

canvas.drawBitmap(this.getBitmap(), lLeftClamp.getWidth(), 0, lPaint);

Bitmap lRightClamp = drawClamp(this.getBitmap());
canvas.drawBitmap(lRightClamp, lLeftClamp.getWidth()+this.getBitmap().getWidth(), 0, lPaint);

Comments 2

  1. Cool, exactly the sort of example I needed. I am trying to do centered vertically tiled horizontally and this should help me get there.

    I had to change the following line

    Shader lShader = new BitmapShader(aBitmap,
    to be
    Shader lShader = new BitmapShader(lBitmap,

    I got a very nasty crash without the change….

Leave a Reply

Your email address will not be published. Required fields are marked *