Android using PorterDuff to combine images - android

So I'm fundamentally not understanding something about PorterDuff and its various modes. I have two images I am trying to combine, one being an aerial image and the other being an alpha mask meant to be overlayed on the aerial so only certain sections show through. I have a system currently where I can correctly overlay the mask onto the other image where only it comes through, but the problem is that in this case I have to have a background color and I need it to be transparent. (similar to the problem here Efficient Bitmap masking with black and white alpha mask in Android)
Bitmap thumbnail = Bitmap.createBitmap(mThumbnailSize, mThumbnailSize, Config.ARGB_8888);
Canvas canvas = new Canvas(thumbnail);
Paint paint = new Paint();
paint.setFilterBitmap(true);
canvas.drawColor(Color.TRANSPARENT);
canvas.drawBitmap(aerial, transformation, paint);
paint = new Paint();
paint.setFilterBitmap(true);
paint.setColorFilter(new PorterDuffColorFilter(Color.WHITE,PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(overlay, transformation, paint);
I feel like I've tried every combination of ColorFilter, XferMode, even drawing the images in the reverse order but nothing seems to work. I feel like I am just completely misunderstanding how the PorterDuff modes work (basing a lot of my information on http://ssp.impulsetrain.com/porterduff.html).
If anyone has any insight on how to accomplish this, insight on what PorterDuff Mode I should use, whether I should be using an ColorFilter or XferMode, anything at all I would really appreciate it.
Thanks in advance

May be I'm late but the solution is to make the background transparent so you get the alpha mask that you already know how to use. Here is a CSharp helper method to convert B/W image to the alpha mask.
private static Bitmap ConvertToAlphaMask(Bitmap mask)
{
float[] src = {
0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
0.3f, 0.59f, 0.11f, 0, 0,
};
var colorMatrix = new ColorMatrix(src);
var filter = new ColorMatrixColorFilter(colorMatrix);
var maskPaint = new Paint();
maskPaint.SetColorFilter(filter);
var alphaMask = Bitmap.CreateBitmap(mask.Width, mask.Height, Bitmap.Config.Argb8888);
var canvas = new Canvas(alphaMask);
canvas.DrawBitmap(mask, 0, 0, maskPaint);
return alphaMask;
}

Related

Android: How to draw this custom shape

I'm new to Android, and I would like to know how to draw this blue shape:
Without using images, of course.
Thanks!
The easy way would be your suggested solution, ie. drawing all circles with no alpha to a bitmap, then draw that bitmap to another one using the desired alpha.
The hard way would be using blend modes, specifically PorterDuff.Mode in Android. An example can be found here.
Also Check this http://softwyer.wordpress.com/2012/01/21/1009/
An example
Bitmap bitmap = Bitmap.createBitmap(b.getWidth(), b.getHeight(), b.getConfig());
Canvas canvas = new Canvas(bitmap);
Paint p = new Paint(Paint.ANTI_ALIAS_FLAG);
p.setColor(Color.BLACK);
canvas.drawRoundRect(new RectF(0, 0, b.getWidth(), b.getHeight()), borderRadius, borderRadius, p);
p.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(b, 0, 0, p);

How to create emboss around a Bitmap?

The popular game Words with Friends draws letter tiles at the game board as a single entity -
You can see a yellow linear gradient applied to all letter tiles in the following screenshot and also an emboss effect on the edge:
In my word game I would like to have similar effects:
So I create a game board sized mBitmap, then draw all tiles into it and finally draw the bitmap into my custom view -
Setup:
setLayerType(View.LAYER_TYPE_SOFTWARE, null);
// create yellow linear gradient
mGradStart = new Point(3 * mWidth / 4, mHeight / 3);
mGradEnd = new Point(mWidth / 4, 2 * mHeight / 3);
LinearGradient gradient = new LinearGradient(
mGradStart.x,
mGradStart.y,
mGradEnd.x,
mGradEnd.y,
new int[]{ 0xCCFFCC00, 0xCCFFCC99, 0xCCFFCC00 },
null,
TileMode.CLAMP);
// create the big bitmap holding all tiles
mBitmap = Bitmap.createBitmap(mWidth, mHeight, Bitmap.Config.ARGB_8888);
mCanvas = new Canvas(mBitmap);
mPaintGrad = new Paint();
mPaintGrad.setShader(gradient);
mPaintEmboss = new Paint();
mPaintEmboss.setShader(gradient);
EmbossMaskFilter filter = new EmbossMaskFilter(
new float[] { 0f, 1f, 0.5f }, 0.8f, 3f, 3f);
mPaintEmboss.setMaskFilter(filter);
Drawing:
#Override
protected void onDraw(Canvas canvas) {
mGameBoard.draw(canvas);
// draw all tiles as rectangles into big bitmap
// (this code will move to onTouchEvent later)
mBitmap.eraseColor(Color.TRANSPARENT);
for (SmallTile tile: mTiles) {
mCanvas.drawRect(
tile.left,
tile.top,
tile.left + tile.width,
tile.top + tile.height,
mPaintGrad);
tile.draw(mCanvas);
}
canvas.drawBitmap(mBitmap, 0, 0, mPaintEmboss); // emboss NOT displayed
canvas.drawText("TEXT WORKS OK", 400, 400, mPaintEmboss); // ebmoss OK
canvas.drawRect(300, 600, 800, 1200, mPaintEmboss); // emboss OK
}
The EmbossMaskFilter effect works OK with drawText() and drawRect() calls, but it does NOT work for the drawBitmap():
My question: is it possible to use some combinations of PorterDuff.Mode (and extractAlpha?) to draw an emboss around my big bitmap?
UPDATE:
By looking at HolographicOutlineHelper.java I have been able to add an outer shadow:
with the following code in MyView.java -
Setup:
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
mScale = getResources().getDisplayMetrics().density;
mGradStart = new Point(3 * mWidth / 4, mHeight / 3);
mGradEnd = new Point(mWidth / 4, 2 * mHeight / 3);
LinearGradient gradient = new LinearGradient(
mGradStart.x,
mGradStart.y,
mGradEnd.x,
mGradEnd.y,
new int[]{ 0xCCFFCC00, 0xCCFFCC99, 0xCCFFCC00 },
null,
TileMode.CLAMP);
mBitmap = Bitmap.createBitmap(mWidth, mHeight, Bitmap.Config.ARGB_8888);
mCanvas = new Canvas(mBitmap);
mPaintGrad = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
mPaintGrad.setShader(gradient);
mPaintBlur = new Paint();
mPaintBlur.setColor(Color.BLACK);
BlurMaskFilter blurFilter = new BlurMaskFilter(mScale * 1, Blur.OUTER);
mPaintBlur.setMaskFilter(blurFilter);
}
Drawing:
private void prepareBitmaps() {
mBitmap.eraseColor(Color.TRANSPARENT);
for (SmallTile tile: mTiles) {
mCanvas.drawRect(
tile.left,
tile.top,
tile.left + tile.width,
tile.top + tile.height,
mPaintGrad);
tile.draw(mCanvas);
}
mAlphaBitmap = mBitmap.extractAlpha(mPaintBlur, mOffset);
}
#Override
protected void onDraw(Canvas canvas) {
mGameBoard.draw(canvas);
canvas.drawBitmap(mAlphaBitmap, mOffset[0], mOffset[1], mPaintBlur);
canvas.drawBitmap(mBitmap, 0, 0, mPaintGrad);
}
but unfortunately the app is acting slow now - and I still don't know how to add an emboss effect around the bitmap.
I'm not sure i got exacly what you need, but if you just want to apply EmbossMaskFilter around some png letter with alpha channel, you can pretty much do this trick with
EmbossMaskFilter filter = new EmbossMaskFilter(new float[]{1, 1, 1}, 0.5f, 0.6f, 2f);
Paint paintEmboss = new Paint();
paintEmboss.setMaskFilter(embossMaskFilter);
Bitmap helperBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas helperCanvas = new Canvas(helperBitmap);
Bitmap alpha = src.extractAlpha();
helperCanvas.drawBitmap(alpha, 0, 0, paintEmboss);
alpha.recycle();
...
canvas.drawBitmap(helperBitmap, 0, 0, anyPaint);
You will never want all of this code in 1 onDraw, because it creates lots of objects in memory. And src.extractAlpha(); creates new Bitmap each time. (Btw i always get out of memory error from your project git . Added mAlphaBitmap.recycle(); and it could at least boot. But it still lagges like hell)
So, i played with your git repository and got some results. Here is demo image and git repo of first commit:
But then i realized, that you don't need EmbossMaskFilter around letters, you need them around rectangles. And it can be done pretty much the same way. Here is how i done this:
Create new helper static Bitmap and Canvas for emboss background, just like mAlphaBitmap
On each prepareBitmaps() paint rects on helper bitmap. Solid color with no alpha.
Extract alpha from created bitmap like this Bitmap alpha = helperCanvas.extractAlpha();
Draw extracted alpha bitmap on helper with paint with emboss filter helperCanvas.drawBitmap(alpha, 0, 0, paintEmboss);
In onDraw print helperBitmap with some alpha before main Bitmap.
Here is screenshot without alpha(because it is much easier to see the shapes this way)
Here is git demo of this version: https://github.com/varren/AndroidEmbossMaskFilterForPng/blob/1d692d576e78bd434252a8a6c6ad2ee9f4c6dbd8/app/src/main/java/de/afarber/mytiles2/MyView.java
And here is essential part of code i changed in your project:
private static final EmbossMaskFilter filter =
new EmbossMaskFilter(new float[]{1, 1, 1}, 0.5f, 0.6f, 2f);
private static Canvas helperCanvas;
private static Paint paintEmboss;
public Canvas getHelperCanvas(int width, int height){
if (mAlphaBitmap == null) {
mAlphaBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
helperCanvas = new Canvas(mAlphaBitmap);
paintEmboss = new Paint();
paintEmboss.setColor(Color.BLACK);
}
return helperCanvas;
}
private void prepareBitmaps() {
mCanvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
helperCanvas = getHelperCanvas(mBitmap.getWidth(),mBitmap.getHeight());
helperCanvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
paintEmboss.setMaskFilter(null);
paintEmboss.setAlpha(255);
for (SmallTile tile: mTiles) {
if (!tile.visible) continue;
helperCanvas.drawRect(tile.left,tile.top,tile.left + tile.width,
tile.top + tile.height,paintEmboss);
mCanvas.drawRect(tile.left, tile.top,tile.left + tile.width,
tile.top + tile.height, mPaintGrad);
tile.draw(mCanvas);
}
paintEmboss.setMaskFilter(filter);
Bitmap alpha = mAlphaBitmap.extractAlpha();
helperCanvas.drawBitmap(alpha, 0, 0, paintEmboss);
}
protected void onDraw(Canvas canvas) {
// ...
paintEmboss.setAlpha(255); //todo change alpha here
if(mAlphaBitmap!= null)canvas.drawBitmap(mAlphaBitmap, 0,0, paintEmboss);
if(mBitmap!= null)canvas.drawBitmap(mBitmap, 0, 0, mPaintGrad);
// ...
}
And the last 3-d step i made is to move everything from onDraw to prepareBitmaps() and preformance is fine now, but we have text destortion on resize. so here is source code for this step.
And here is kinda fine working final solution. Moving all paints with filters solved preformance issues, but i think there are still better options to implement this. As i said erlier i don't know is it what you need, but this code pretty much creates Emboss around Bitmap
PS: kinda cool effect when splitting and adding cells together
PS2: new EmbossMaskFilter(new float[] { 0f, 1f, 0.5f }, 0.8f, 3f, 3f); this will not look the same on diferent devices with diferent screen resolution
Here's a suggestion using a custom layout.
You'll need your own layout for the scrabble board. Since it's grid, this should be pretty easy to code.
The basic idea is to have a set of PNG shadow images, one for each type of combination of adjacent cells. In your layout onDraw(), draw the shadows first, then draw the tile in onLayout().
In onDraw(), iterate through your array of tiles placeholders. If you have a tile, then for each edge, inspect the adjacent cells. Depending on what's adjacent, choose the correct shadow image and draw it.
You can reduce the number of shadow images substantially by having a shadow image which is exactly the width of a tile and then specializing the corner area: one for 270 degrees, one for straight alignment, one for 90 degrees.
I don't know if using porter-duff can help since you still need to determine all these "edge" cases (no pun intended).

Android Imagebutton with gradient background

For days I tried to implement a simple Imagebutton in Android, using a dynamic LinearGradient as background. I want the base design from android.R.drawable.btn_default, which is colored starting from the left edge of the button to a value given in percent from v = 0-100%(right edge). The edge between the left and right part of the button should be sharp (like an equalizer). For any suggestions without NullException errors I would be very thankful!
EDIT 29.07.14
Here is the code snippet, working without errors:
Drawable dr = getResources().getDrawable(android.R.drawable.btn_default);
Bitmap bitmap = Bitmap.createBitmap(dr.getIntrinsicWidth(), dr.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
dr.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
dr.draw(canvas);
Paint paint = new Paint();
paint.setXfermode(new PorterDuffXfermode(Mode.MULTIPLY));
paint.setShader(new LinearGradient(0, 0, canvas.getWidth()*7*vol, 0, new int[] { Color.GREEN, Color.TRANSPARENT }, new float[] { 0, 1 }, Shader.TileMode.CLAMP));
canvas.drawRect(0, 0, canvas.getWidth(), canvas.getHeight(), paint);
mButtonSpeech.setBackground(new BitmapDrawable(getResources(), bitmap));
But even without the middle part of my code, adding the gradient to the canvas, the button background does not look like I expect it (it is to small and in the center not colored like the other buttons, where I set the backgrund by:
mButtonDraw.setBackgroundResource(android.R.drawable.btn_default);
If I also draw the Paint into Canvas, I would expect the default button background, colored in the left part, like I could do it with setColorFilter().

Android Mask two Bitmap clear border

I'm using the mask a bitmap with another. The operation succeeds well, unfortunately the result of masking seen a slight black border, as you can see in the image:
How do I remove this border? in the source image is not there.
I'll post the code I'm using:
public Bitmap mask(Bitmap source) {
Bitmap targetBitmap = Bitmap.createBitmap(getWidth(),getHeight(),
Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(targetBitmap);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
paint.setAntiAlias(true);
paint.setDither(true);
canvas.drawBitmap(source, 0, 0, null);
canvas.drawBitmap(getMask(), 0, 0, paint);
paint.setXfermode(null);
return targetBitmap;
}
where getMask () returns the Bitmap that represents the figure of the Puzzle.
I hope to receive your help, thank you all
Sorry for my english :-)
UPDATE:
the black border is what I point out in this picture:
UPDATE:
place the sequence of transformation. The third image would be identical to the first but without color. The problem is the black edge of the puzzle.
I hope to be more clear:
The way I draw images with mask is kind of the other way around from what you do.
public Bitmap mask(Bitmap source) {
Bitmap targetBitmap = Bitmap.createBitmap(getWidth(),getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(targetBitmap);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
// paint.setAntiAlias(true); // you've already set this in the constructor
paint.setDither(true);
canvas.drawBitmap(getMask(), 0, 0, null);
canvas.drawBitmap(source, 0, 0, paint);
// paint.setXfermode(null); // no need for this
return targetBitmap;
}
Note that PorterDuff.Mode is set to SRC_IN (not DST_in) and that the mask is drawn first and then the image on top of that mask. With this approach you can also draw the previous source as the base mask, add the new (puzzle) mask and then draw the final source/image on top of that with SRC_IN paint to add new puzzle pieces each time.
If that doesn't solve the black border, check that your mask doesn't have feathered (transparent) edges that might be causing these problems.
Also, ANTI_ALIAS_FLAG doesn't do anything on textures. If you want smoothly scaled textures use paint.setFilterBitmap(true);

how to set additive overlay of jpg images to achieve transparency

I need to overlay two images in live wallpaper. The overlay images is the jpg which needs to be set to "additive" overlay. it adds the pixel value rather than calculating the transparency. how can i achieve this in android ?
You can make use of Android's Bitmap and Drawable classes mixed with Canvas, and try something like in this snippet:
public static Drawable mergeImage(Drawable orig, Drawable over, int left, int top) {
Bitmap original = ((BitmapDrawable)orig).getBitmap();
Bitmap overlay = ((BitmapDrawable)over).getBitmap();
Bitmap result = Bitmap.createBitmap(original.getWidth(), original.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(result);
Paint paint = new Paint();
paint.setAntiAlias(true);
canvas.drawBitmap(original, 0, 0, paint);
canvas.drawBitmap(overlay, left, top, paint);
return new BitmapDrawable(result);
}
I've coded a photo image gridview overlayered with "online status" using the above lines. Hope that it works for you too.
A more general approach may be to create a PorterDuffXfermode with your wanted PorterDuffMode and then set it on the Paint object that you use with your canvas, as referenced in mthama's answer but substituting some lines. This allows you to use other Porter-Duff modes as wanted/needed.
Paint paint = new Paint();
paint.setAntiAlias(true);
canvas.drawBitmap(original, 0, 0, paint);
paint.setXferMode(new PorterDuffXferMode(PorterDuff.Mode.OVERLAY));
canvas.drawBitmap(overlay, left, top, paint);
Mind you, I haven't tried this, so go with mthama's answer. :)

Categories

Resources