I'm fairly new to Android programming. I'm trying to create an animation of a bitmap image using Canvas in Android. I am using setAlpha() to manipulate the opacity of the bitmap. My drawFrame() method includes the following bit:
c = holder.lockCanvas();
drawScene(c, paint);
holder.unlockCanvasAndPost(c);
My drawScene() includes this bit:
Paint transparencyValue = new Paint();
transparencyValue.setAlpha(paint);
canvas.drawBitmap(boom.getImage(), logoToBoom.getX(), logoToBoom.getY(),
transparencyValue);
I imagine I have to insert a loop to modify paint from 0 to 255 and back down. So far it hasn't worked, but I am probably doing something wrong. Could anyone please recommend something?
EDIT: Here is my code for the Runnable. paint is a private double set to 255. boom_activated is a boolean that becomes true if the onTouchEvent enabled it. It should stay true until the Runnable disables it (setBoomState(false);). For some reason it's still not drawing the bitmap at the decreasing opacity. Is the code below valid, or am I missing something?
private final Runnable DrawSceneThread = new Runnable() {
public void run() {
if (boom_activated && paint <= 0) {
paint = 0;
drawFrame();
setBoomState(false);
paint = 255;
} else if (boom_activated && paint >= 0) {
drawFrame();
paint -= 0.7;
} else {
drawFrame();
}`
In my drawScene() I have this line:
scene_handler.postDelayed(DrawSceneThread, 25);
What you have to do is to animate the opacity values over time. You need to use a handler to update the alpha values and then draw the bitmap in your onDraw function. Have a look at this tutorial to get a better idea about updating the UI through handlers: http://developer.android.com/resources/articles/timed-ui-updates.html
Refer to this topic
How to change a bitmap's opacity?
Also, I would recommend to take your Paint instance and paint variable out of your drawScene and declare it in a global scope so you can reuse it. It would hurt performance when recreating it over and over.
Related
I am trying to create a spin in android. Well i have used a library code to create spin like below image:
Spin Example in android
The help i want is to fit the spin images to the arc.
The method canvas.drawArc() only accept the paint also i tried with canvas.drawBitmap() but that does not fix in the arc shape.
Here is the Sample code for creating a slice of the spin with background color:
Paint mArcPaint = new Paint();
private RectF mRange = new RectF();
protected void onDraw(Canvas canvas) {
for (int i = 0; i < 6 i++) {
mArcPaint.setStyle(Paint.Style.FILL);
mArcPaint.setColor(mLuckyItemList.get(i).color); //Color of a Pie
canvas.drawArc(mRange, tmpAngle, sweepAngle, true, mArcPaint); //Different Float value instead of angles
}
}
I hope somebody from community solves my problem.
Thanks in Advance
Try this Libarry https://github.com/adef145/SpinningWheelAndroid SpinningWheelAndroid
Create a BitmapShader, select it to the paint object then draw an arc.
I am trying to draw increasing circles in a TextureView. The centre of all circles is the same. I then try to increase the drawn Circle until a specific limit is reached. Then I want to clear the canvas and start over again. However using my code (see below), the canvas seems to never be cleared. Actually it flashes white shortly when it should be cleared, but then when the first circle in the next cycle is drawn (after attempting to clear canvas), all previous circles reappear and the whole animation seems to go crazy. After letting it run for several seconds I am left with dozens of circles (some overlapping) instead of only approximately 4 per cycle. Furthermore they do not have the radius I gave them (basically my code ends up drawing numerous circles of random sizes). Spent several days trying different things, but nothing seems to help.
Here's my code:
paint.setColor(Color.argb(opac, 177, 177, 177));
stroke = 5;
paint.setStrokeWidth(stroke);
radius = 10;
Canvas canvas = new Canvas();
Boolean clear = false;
//Added these two lines following advice from a previous answer:
Paint clearPaint = new Paint();
clearPaint.setXfermode(new PorterDuffXfermode(Mode.CLEAR));
while (mRunning && !Thread.interrupted()) {
canvas = mSurface.lockCanvas(null);
try {
if(clear){
canvas.drawPaint(clearPaint); //This line should clear the canvas.
clear = false;
}else{
canvas.drawCircle(circleX, circleY, radius, paint);
}
} finally {
mSurface.unlockCanvasAndPost(canvas);
}
if(radius+15 <= circleY-stroke/2){
radius+=15;
}else{
radius = 10;
clear = true;
}
try {
Thread.sleep(360);
} catch (InterruptedException e) {
// Interrupted
}
Would really appreciate it if someone could help me out here. I wasn't able to proceed with my project for several weeks now due to this problem.
Create a new Paint Instance for just clearing the canvas
Paint clearPaint = new Paint();
clearPaint.setXfermode(new PorterDuffXfermode(Mode.CLEAR));
In your if() block for clearing the canvas, paint it with the above instance of Paint
if(clear){
canvas.drawPaint(clearPaint);
clear = false;
}
So I'm trying to make custom buttons, for which I need to combine different parts of the button background. To do this I figured using a FrameBuffer would work, however it did not give viable results. Therefore I attempted to test my FrameBuffer drawing method, by writing a simple test method, which returns a texture that is drawn to the display at every render() call. This method is here (note that it is a test method, so it may be a little poorly optimized):
private Texture test()
{
BitmapFont f = ReverseBlade.fontTitle;
f.setColor(Color.LIGHT_GRAY);
FrameBuffer fbo = new FrameBuffer(Format.RGBA8888, (int)f.getBounds("Hi").width, (int)f.getBounds("Hi").height, false);
Batch b = ReverseBlade.batch;
OrthographicCamera c = new OrthographicCamera(fbo.getWidth(), fbo.getHeight());
c.setToOrtho(false);
c.update();
b.setProjectionMatrix(c.combined);
fbo.begin();
b.begin();
f.draw(b, "Hi", 0, 0);
b.end();
fbo.end();
Texture t = fbo.getColorBufferTexture();
fbo.dispose();
b.setProjectionMatrix(ReverseBlade.camera.combined);
return t;
}
However, nothing is displayed. The screen is dark... I have tried without the camera and multiple other variations that I can no longer remember. What am I doing wrong?
Half Solution
What I ended up having to do is to make a new Matrix4 object for the FrameBuffer like this:
Matrix4 m = new Matrix4();
m.setToOrtho2D(0, 0, fbo.getWidth(), fbo.getHeight());
batch.setProjectionMatrix(m);
However, this makes everything that is drawn be upside down, like this:
I think the fbo.dispose() call is destroying more than you want.
See the source and notice where it destroys the colorTexture, which is the result of getColorBufferTexture().
I think this could be considered a bug in Libgdx. The color texture is generally something that should have a very different lifetime than the FBO, so cleaning up the texture seems a bit too aggressive. However, trying to figure out which cases to clean the texture up is probably complicated.....
So following what I added with the Half Solution, all I had to do was create a new Sprite object with the texture from the FBo and call flip(false, true)!
May be this is a workaround to dispose() the framebuffer and keeping the texture alive. I do the following:
public class TextureSaveFBO extends FrameBuffer {
static final Texture DUMMY = new Texture(1, 1, Format.RGB565) {
public void dispose() {
};
};
public TextureSaveFBO(Format format, int width, int height,
boolean hasDepth) {
super(format, width, height, hasDepth);
}
#Override
public void dispose() {
// prevents the real texture of dispose()
Texture t = colorTexture;
colorTexture = DUMMY;
super.dispose();
colorTexture = t;
}
}
Just a precisation:
OrthographicCamera c = new OrthographicCamera(fbo.getWidth(), fbo.getHeight());
c.setToOrtho(false);
This is potentially harmful unless you know what you are doing: c.setOrtho(false) does the following:
Sets this camera to an orthographic projection using a viewport fitting the screen resolution, centered at (Gdx.graphics.getWidth()/2, Gdx.graphics.getHeight()/2), with the y-axis pointing up or down.
So even if you specified in the OrthographicCamera's constructor that you want the viewport to be of the frame buffer size, you are overwriting that with the following call to a viewport covering the screen size and centered to the screen center.
You should probably do:
camera.setToOrtho(false, fbo.getWidth(), fbo.getHeight());
Issue solved since LibGDX 1.6.5.
It's now possible to override disposeColorBuffer method to not dispose rendered texture.
A LinearGradientPaint object from java.awt may appear nice once painted, but there's a problem I'm having with it for painting an animated background in some kind of game model that's taking me long to build.
I want to paint an animated rainbow gradient on the background using the Graphics2D paint object, except that when I do so, I notice a lot of lag in repainting the panel. It should repaint itself at least 30 frames per second, which is only possible if the Paint object the graphics object uses is not a rainbow gradient.
Even running it as a separate thread will not do the trick. Below is the code for what I am trying to do at the end of each frame:
gamePanel.executor.execute(new Runnable(){
public void run()
{
while(true)
{
if (Background.selectedBackgroundIndex >= Background.SKY_HORIZON_GRADIENT_PAINT &&
Background.selectedBackgroundIndex < Background.SPACE_PAINT)
{
float displacementValue = 1.0f;
if (Background.backgroundShape.y < ((-2990.0f) + CannonShooterModel.gamePanel.getSize().height) && gamePanel.horizonGoingDown)
gamePanel.horizonGoingDown = false;
else if (Background.backgroundShape.y > (-10.0f) && !gamePanel.horizonGoingDown)
gamePanel.horizonGoingDown = true;
Point2D.Double startPoint = (Point2D.Double)(((LinearGradientPaint)Background.background).getStartPoint()),
endPoint = (Point2D.Double)(((LinearGradientPaint)Background.background).getEndPoint());
if (gamePanel.horizonGoingDown)
Background.backgroundShape.y -= displacementValue;
else
Background.backgroundShape.y += displacementValue;
startPoint.setLocation(0, Background.backgroundShape.y);
endPoint.setLocation(0, Background.horizonGradientPaintHeight + Background.backgroundShape.y);
// Should be done in another thread, particularly in arithmetic calculations.
Background.background = new LinearGradientPaint(startPoint, endPoint,
((LinearGradientPaint)Background.background).getFractions(),
((LinearGradientPaint)Background.background).getColors());
}
for (int a = 0; a < PlayerUnit.weapon.bullets.length; a++)
{
if (PlayerUnit.weapon.bullets[a] != null)
{
if (PlayerUnit.weapon instanceof Pistol &&
((Ellipse2D.Float)PlayerUnit.weapon.bullets[a]).x + ((Pistol)PlayerUnit.weapon).bulletWidth >= 0 &&
((Ellipse2D.Float)PlayerUnit.weapon.bullets[a]).x <= CannonShooterModel.gamePanel.getSize().width &&
((Ellipse2D.Float)PlayerUnit.weapon.bullets[a]).y + ((Pistol)PlayerUnit.weapon).bulletWidth >= 0)
{
if (PlayerUnit.weapon.weaponAngles[a] >= 0)
((Ellipse2D.Float)PlayerUnit.weapon.bullets[a]).x +=
PlayerUnit.weapon.bulletSpeed * Math.cos(PlayerUnit.weapon.weaponAngles[a]);
else
((Ellipse2D.Float)PlayerUnit.weapon.bullets[a]).x -=
PlayerUnit.weapon.bulletSpeed * Math.cos(PlayerUnit.weapon.weaponAngles[a]);
if (PlayerUnit.weapon.weaponAngles[a] >= 0)
((Ellipse2D.Float)PlayerUnit.weapon.bullets[a]).y -=
PlayerUnit.weapon.bulletSpeed * Math.sin(PlayerUnit.weapon.weaponAngles[a]);
else
((Ellipse2D.Float)PlayerUnit.weapon.bullets[a]).y +=
PlayerUnit.weapon.bulletSpeed * Math.sin(PlayerUnit.weapon.weaponAngles[a]);
}
else
PlayerUnit.weapon.bullets[a] = null;
}
}
//System.out.println(Background.backgroundShape.y);
repaint();
try
{
Thread.sleep(1000 / 60);
}
catch (InterruptedException ex)
{
}
}
}
});
The classes Background, PlayerUnit, and CannonShooterModel are important to my game model. It's an upright shooting game supposed to be designed with various weapons and enemies.
This rainbow gradient I have uses an array of eight different Color objects. For every frame passed through, I change the y-coordinate for both Point2D.Float objects required for the gradient paint as desired. In order for the animation to work, I have to actually instantiate another object of LinearGradientPaint again, with some of the previous properties from the previous object, and have it be referenced by the variable background of type Paint.
Problem is, LinearGradientPaint does not have a method to where you can do a translate on the two end points, and the get methods do not return the actual object that LinearGradientPaint object contains. (what I mean is, the get methods return a new object of Point2D with the same values as those part of the LinearGradientPaint object.)
For every frame passed, I have to change not only the y-coordinate property of the shape that's associated with the gradient, but also set the locations of the two Point2D objects that are needed to instantiate LinearGradientPaint once again.
I would love to re-explain this much simpler, because I can have trouble with some knowledge of English, even though this is my primary language. Please let me know if you need re-explanation.
There are a couple of solutions you might try.
Instead of filling the entire paintable area, you could create a BufferedImage whose width is 1 pixel and height equal to the area you want to fill (assuming you are fill vertically). You would then apply the LinearGradientPaint to this BufferedImage's Graphics2D and fill it (don't forget to dispose of the Graphics context when your done).
Then, you would simply use Graphics#drawImage(Image, x, y, width, height, ImageObserver) to actually paint the image. Generally speaking, it appears that it's faster to rescale an image then it is to fill it with a LinearGradientPaint, especially when you consider you are only stretching the image horizontally.
The other choice would be to generate a basic BufferedImage which had the LinearGradientPaint already applied and you would simply paint this offset as required. This would probably require you to paint it at least twice to allow it to "stitch" toegther...
If you are just making the background gradient move up and down, could you write it to an image at initialization and then move and wrap the image vertically?
I'm doing the following to a Canvas object.
graphics.setColor(BLUE);
graphics.fill(new Rectangle2D.Double(x, y, width, height));
I'd like to fade in the fill colour to create a smooth transition from the canvas background colour to the new colour (and possibly fade out whatever colour was originally there).
I've played with this kind of thing (setting the graphics object's composite to an AlphaComposite which a Timer updating the alpha value every n milliseconds) but I get flickering.
I'm wondering what general concept I'm missing.
Thanks for any pointers.
First of all, how could you be using the AWT? It is quite outdated. I reccomend you switch to swing, mainly because swing has double buffering, which would remove your flicker.
Your application does exactly what you tell it to do. If you want to make a fade-in effect, you have to determine what kind of color changes you want to make, create a function which does it, and implement the fade itself.
I'd approach it like that:
class FadeEffect{
int totalDurationMs;
int elapsedDurationMs;
Color initialColor;
Color finalColor;
Color getColor(int durationDelta) {
elapsedDurationMs += durationDelta;
if (elapsedDurationMs > totalDurationMs) {
return finalColor;
}
double progress = 1.0d*elapsedDurationMs/totalDurationMs;
return new Color( (int)(finalColor.getRed()-initialColor.getRed())*progress,
(int)(finalColor.getGreen()-initialColor.getGreen())*progress,
(int)(finalColor.getBlue()-initialColor.getBlue())*progress);
}
//getters, setters, etc
}
As for the flickering issue: make sure you are using double buffering - either in your component, or by manually drawing on a off-screen buffer (image) and only posting the image to the screen when the drawing is complete.
Here is a sample code from my Graphic2D app doing the double buffering:
private VolatileImage vImg;
#Override
public void paint(Graphics g) {
if (gc==null) gc = this.getGraphicsConfiguration();
do {
boolean sizeChanged = false;
sizeChanged = (vImg!=null&&(vImg.getWidth()!=getWidth()|| vImg.getHeight()!=getHeight()));
if (vImg == null || vImg.validate(gc) == VolatileImage.IMAGE_INCOMPATIBLE
|| sizeChanged) {
vImg = gc.createCompatibleVolatileImage(getWidth(), getHeight());
vImg.setAccelerationPriority(1);
}
final Graphics gimg = vImg.getGraphics();
if (gimg instanceof Graphics2D) {
renderContents((Graphics2D) gimg);
gimg.dispose();
g.drawImage(vImg, 0, 0, null);
} else {
throw new UnsupportedOperationException("Rendering impossible, graphics are not of Graphics2D class");
}
} while (vImg.contentsLost());
updateAnimationNo();
}