PorterDuffXfermode DST_IN not working as expected - java

So I'm trying to speed up some drawing we're doing (drawing a portion of an arc with alpha transparency) and was attempting to cache the entire arc into a separate bitmap, and show it selectively with an alpha mask.
From the research I've done (the Xfermodes API demo for Android, this example, and this tool), if I have for example the following two graphics:
and draw using the following:
Xfermode DST_IN = new PorterDuffXfermode(PorterDuff.Mode.DST_IN);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
canvas.drawBitmap(circle, 0, 0, paint);
paint.setXfermode(DST_IN);
canvas.drawBitmap(arc, 0, 0, paint);
paint.setXfermode(null);
I should get this result:
Where the destination image (the circle) is clipped to the area where the source image (the arc) is drawn. Instead, I get the full circle. If I just draw the arc, it appears in the correct location, and if I use DST_OUT instead, I get the inverse of the expected result (the other three quadrants of the circle).
I've also made sure to disable hardware rendering for this view, in case there was an issue with this Xfermode, but it doesn't make a difference.
I broke it out into a separate project at the simplest level trying to get it to work, and using the following code, I still have the same problem:
public class ClippedView extends View {
private Xfermode DST_IN, DST_OUT;
private Paint paint;
public ClippedView(Context context) {
super(context);
init();
}
private void init() {
setLayoutParams(new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
this.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
DST_IN = new PorterDuffXfermode(PorterDuff.Mode.DST_IN);
DST_OUT = new PorterDuffXfermode(PorterDuff.Mode.DST_OUT);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
paint.setColor(Color.GREEN);
canvas.drawRect(0, 0, getWidth() / 2, getHeight() / 2, paint);
paint.setColor(Color.BLACK);
paint.setXfermode(DST_IN);
canvas.drawCircle(getWidth() / 2, getHeight() / 2, getWidth() / 2, paint);
paint.setXfermode(null);
}
}
Am I using it wrong? Am I just missing something? Have I found a bug? :)

There's a much cheaper and easier way to achieve this: use clipping. Canvas.clipRect() is enough. Your solution is burning a lot of fillrate. You can get the effect you want by using SRC_IN instead of DST_IN. Be careful though: it will work only in a transparent Bitmap or in layer. When you draw directly on screen, the destination is already filled by the window background.

Related

RadialGradientPaint Equivalent in Android

I am drawing a radial gradient circle on an image like this
I have java code for this
private void drawRadialGradientCircleJava(String imagePath, double posX, double posY, float radius, String outputPath) throws IOException{
BufferedImage city = ImageIO.read(new File(imagePath));
BufferedImage mask = new BufferedImage(city.getWidth(), city.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = mask.createGraphics();
Color transparent = new Color(255, 0, 0, 0);
Color fill = Color.RED;
RadialGradientPaint rgp = new RadialGradientPaint(
new Point2D.Double(posX, posY),
radius,
new float[]{0f, 0.75f, 1f},
new Color[]{transparent, transparent, fill});
g2d.setPaint(rgp);
g2d.fill(new Rectangle(0, 0, mask.getWidth(), mask.getHeight()));
g2d.dispose();
BufferedImage masked = new BufferedImage(city.getWidth(), city.getHeight(), BufferedImage.TYPE_INT_ARGB);
g2d = masked.createGraphics();
g2d.setColor(Color.RED);
g2d.fillRect(0, 0, masked.getWidth(), masked.getHeight());
g2d.drawImage(city, 0, 0, null);
g2d.setComposite(AlphaComposite.DstAtop);
g2d.drawImage(mask, 0, 0, null);
g2d.dispose();
ImageIO.write(masked,"png", new File(outputPath));
}
I want to do same thing in Android, I have an image view in which I have an image, now I want to touch a point in image and draw this transparent circle around that point
I have following Android code as well but id doesn't draw anything on the image
private void drawRadialGradientCircleAndroid(ImageView imageView, float posX,
float posY, float radius) throws IOException {
RadialGradient gradient = new RadialGradient(posX, posY, radius, Color.TRANSPARENT,
Color.TRANSPARENT, android.graphics.Shader.TileMode.CLAMP);
Paint p = new Paint();
p.setDither(true);
p.setShader(gradient);
Bitmap bm = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
Bitmap bmOverlay = Bitmap.createBitmap(bm.getWidth(), bm.getHeight(), bm.getConfig());
Canvas canvas = new Canvas(bmOverlay);
canvas.drawBitmap(bm, new Matrix(), null);
canvas.drawCircle(posY, posX, radius, p);
imageView.setImageBitmap(bmOverlay);
}
Please help how can I achieve this in Android.
We should migrate this to the answer boxes.
OP has basically got it here- and in fact the OP's revised gist is brilliant.
Some general tips regarding the first attempt in the question:
1) In protected void onSizeChanged(int w, int h, int oldw, int oldh):
width = w; there is no reason why you can't call getWidth() when you require this. The reason it's advisable is because the View's internal width is set quite late after onMeasure. Consequently, onDraw may be the next time you want a most up to date version, so use the getter there.
mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);. Creating a bitmap is an expensive and memory intensive operation. Unless you want to write a bitmap to a file, or send it to a BitmapDrawable for an ImageView or something, you don't need to do this. Especially with effects drawn onto the UI with android's graphics library.
mCanvas = new Canvas(mBitmap); followed by a draw operation onto the new canvas. This is never needed. And yet I've seen it (not work) in many code bases and attempts. I think it's the fault of an old stack overflow post that got people doing this so that they could transform a canvas on a custom view without effecting the drawing onto the rest of the canvas. Incidentally, if you need this, use .restore() and .save() instead. If you see new Canvas, be suspicious.
2) onDraw(...):
Yes, you need to avoid doing things in onDraw, like, creating objects, or any heavy processing. But you still need to do the things in onDraw you need to do in onDraw!
So here you simply need to call : canvas.drawCircle(float cx, float cy, float radius, Paint paint) with arguments as per the docs.
This really isn't that sinful for onDraw. If you're worried about calling this too much, as might be the case if your entire button is animating across the screen, you need to use hardware acceleration available in later API versions, as will be detailed in an article called Optimizing the View; very helpful reading if you're using lots of custom drawn views.
3) That pesky radial gradient. The next issue you had is that you quite rightly created your paint in an initmethod so that the object creation was off the draw. But then quite rightly it will have IllegalArgumentExceptioned (I think) on you because at that stage the getHeight() of the view was 0. You tried passing in small pixel values- that won't work unless you know some magic about screen sizes.
This isn't your issue as much as the annoying view cycle at the heart of Android's design patterns. The fix though is easy enough: simply use a later part of the view's drawing process after the onMeasure call to set the paint filter.
But there are some issues with getting this right, namely that sometimes, annoyingly, onDraw gets called before the point at which you'd expect it. The result would be your paint is null and you wouldn't get the desired behavior.
I have found a more robust solution is simply to do a cheeky and naughty little null check in the onDraw and then once only construct the paint object there. It's not strictly speaking optimal, but given the complex way in which the Paint objects hook up with Android's graphics native layer better than trying to straddle the paint configuration and construction in many frequently called places. And it makes for darn clearer code.
This would look like (amending your gist):
#Override
protected void onDraw(final Canvas canvas) {
super.onDraw(canvas);
if (mPaint == null) {
mPaint = new Paint();
mPaint.setColor(Color.BLACK);
mPaint.setStrokeWidth(1);
mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
mPaint.setShader(new RadialGradient(getWidth() / 2, getHeight() / 2,
getHeight() / 3, Color.TRANSPARENT, Color.BLACK, TileMode.MIRROR));
}
width = getWidth();
height = getHeight();
canvas.drawCircle(width / 2, height / 2, height / 3, mPaint);
}
So note a few changes- I think from your description you want the two colours swapped round in the arguments, also don't forget to center the center of your gradient in your view: width/2 and height/2 arguments.
Best of luck!

LibGDX - Nothing on screen changes when translating camera

I'm using a GestureListener to try and create a panning menu, but even though the camera's coordinates are being changed and it's being updated, nothing moves. I think it might be because the stage is drawing relative to the camera but I'm not sure how I would change that.
How I'm going about it:
camera = new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
...
gesture = new GestureDetector(this);
InputMultiplexer im = new InputMultiplexer();
im.addProcessor(gesture);
im.addProcessor(stage);
Gdx.input.setInputProcessor(im);
} //end initialization of CustomizeScreen
public void render(float delta) {
Gdx.gl.glClearColor(0.2f, 0.2f, 0.2f, 1);
Gdx.gl.glClear(GL30.GL_COLOR_BUFFER_BIT);
stage.act(Math.min(Gdx.graphics.getDeltaTime(), 1 / 60f)); //0, 18, 31 for layer style
stage.draw();
Table.drawDebug(stage);
batch.setProjectionMatrix(camera.combined);
g.batch.begin();
g.font.setScale(2);
g.font.setColor(Color.WHITE);
g.font.draw(g.batch, "Coins: " + Filer.getCoins(), 15, Gdx.graphics.getHeight() - 15);
g.font.draw(g.batch, message, 0, 150);
g.batch.end();
camera.update();
}
...
#Override
public boolean pan(float x, float y, float deltaX, float deltaY) {
message = "Pan, delta:" + Float.toString(deltaX) +
"," + Float.toString(deltaY);
camera.translate(deltaX, 0, 0);
camera.update();
return false;
}
I've checked for camera coordinates (camera.position.x) in the update method, so I know it's actually changing something. But all my buttons remain the same. They are placed in thirds of the screen width (Gdx.graphics.getWidth() / 3).
Am I missing something, or doing it wrong? I'd think I'm doing it correctly based on everything I'm found on Google.
Thanks :)
The Stage class has different constructors. Some of those constructors take a Viewport, which contains a Camera. If you use a constructor without Viewport, the Stage creates a new Viewport with a new Camera.
In that case it will use the created Viewport (and Camera) for all it's drawing, unless you switch the Viewport by calling setViewport.
As you don't show, how you create the Stage i am not sure if thats the porblem in your case, but if that is the problem, you can solve it by creating a Viewport with your Camera and passing it to the Stage or by changing the Camera of the Viewport (stage.getViewport().setCamera(myCamera)).
Hope it helps.

Add text with grey background to pictures like Snapchat does? Android/Java

Bitmap newBm = ...
Canvas canvas = new Canvas(newBm);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(Color.WHITE);
paint.setTextSize((int) (44 * scale));
Rect bounds = new Rect();
paint.getTextBounds(gText, 0, gText.length(), bounds);
canvas.drawText(gText, x, y, paint);
I drew text on the Bitmap like so. How could I get a grey background that is the same height as the text but covers the whole screen??
You could use a Rect. Before drawing the text draw the Rect to the screen:
int screenWidth = getApplicationContext().getResources().getDisplayMetrics().widthPixels;
Rect greyBack = new Rect(0,top,screenWidth,bottom);
Paint paint = new Paint();
paint.setARGB(128, 100, 100, 100); //added alpha because Snapchat has translucent //grey background
canvas.drawRect(greyBack, paint);
top and bottom need to be coordinates above and below the text. You could use y's value and take away a bit for top and add a bit for bottom. How much you add/subtract is up to you and changes the height of the greyBack background.
The best way to see and learn how these sort of things are done with well written code is to look at the android source code itself. For example here is the onDraw method for a TextView it includes additional stuff you won't probably need like compoundPadding, but you can follow it through and get the basic concept of how it's done.

Why this code work only once [Android-canvas]

I want to draw circle in canvas. I use function to do id:
public static void add()
{
float a = 20 + (new Random()).nextInt(width-40);
float b = 20 + (new Random()).nextInt(height-40);
paint.setColor(Color.rgb(13, 13, 13));
c.drawCircle(a, b, r, paint);
paint.setColor(Color.rgb(119, 119, 119));
c.drawCircle(a, b, r-3, paint);
}
It works only once, when it called from "onDraw".
p.s.
paint, width, height, c - public varibles.
UPD.:
protected void onDraw(Canvas canv)
{
super.onDraw(canv);
c = canv;
paint = new Paint();
paint.setStyle(Paint.Style.FILL);
paint.setAntiAlias(true);
paint.setColor(Color.WHITE);
c.drawPaint(paint);
add();
}
onDraw() will be called whenever the view needs to re-draw itself. This can be due to many reasons, like layout changing, scrolling etc.
You can also call invalidate() on a View to cause a re-draw.
If you are going to draw at a very high rate, like touch painting or some game etc, consider using a TextureView instead.
I did it as follows.
1) Define a custom View.
2) on its onDraw method, do this creating/showing circle.
3) call invalidate() method in the last line of onDraw method of custom View.
let me know if it works

libGDX Moving orthographic camera down a texture

I've been trying to create a game where there's a person falling. The size of my background texture is 480x3200, and I'm trying to create the game so that the camera keeps the person in the middle of the screen while falling down, and then stops at the bottom. But I can't get my background is extend beyond the screen it starts in, and then be able to see the rest of the image.
All of my code does right now is scale down the 480x3200 image down to fit onto my current screen (which I set to be 480x800), and then as the person falls, the background doesn't change.
Here's my WorldRenderer class where I've tried to do different things but every time, I can never get the person to see a different part of the image when it starts moving down.
public WorldRenderer(SpriteBatch b, World w) {
this.world = w;
this.cam = new OrthographicCamera(CAMERA_WIDTH, CAMERA_HEIGHT);
this.cam.position.set(CAMERA_WIDTH / 2, Person.position.y,0);
this.cam.setToOrtho(false, CAMERA_WIDTH, CAMERA_HEIGHT);
this.cam.update();
spriteBatch = b;
loadTextures();
}
public void render(float delta) {
person = world.getPerson();
moveCamera();
cam.update();
spriteBatch.setProjectionMatrix(cam.combined);
spriteBatch.disableBlending();
spriteBatch.begin();
renderBackground();
spriteBatch.end();
spriteBatch.enableBlending();
spriteBatch.begin();
renderObjects();
spriteBatch.end();
}
private void moveCamera() {
cam.position.set(cam.position.x, Person.position.y, 0);
cam.update();
}
private void renderObjects() {
renderPerson();
renderBlocks();
renderPlatforms();
}
private void renderBackground() {
spriteBatch.draw(backgroundTexture, cam.position.x - CAMERA_WIDTH / 2, cam.position.y - CAMERA_HEIGHT / 2, CAMERA_WIDTH, CAMERA_HEIGHT);
}
}
Does anyone have any suggestions?
Edit:
Thanks, I changed the draw in renderBackground to
spriteBatch.draw(backgroundTexture,0,0, CAMERA_WIDTH, CAMERA_HEIGHT * 4); and it works now.
spriteBatch.draw(backgroundTexture, cam.position.x - CAMERA_WIDTH / 2,
cam.position.y - CAMERA_HEIGHT / 2, CAMERA_WIDTH, CAMERA_HEIGHT);
This code is drawing the background image relative to the camera's position. That's why changing the camera's position has no effect on the background image's position. Change it to something like this:
spriteBatch.draw(backgroundTexture,0,0);
Or u can simply use ParrallaxBackground and ParrallaxLayer class
This way u dont have to manage ur camera
Its done in an optimized manner in the mentioned class.

Categories