I have a custom view that draws a few circles and about 10 arches that are constantly updating (rotation and size change). I am trying to animate this whole process, but I couldn't find any good practices for doing so under Canvas (I know the basics - use dp instead of px and so on), but I don't know hot to properly do the animation part.
Right now I'm iterating trough all of my objects, perform some calculations to determine the future position and draw them, but it looks choppy. Here is what I'm currently doing:
#Override
protected void onDraw(Canvas canvas) {
for(Arch arch : arches) {
arch.update();
canvas.drawArc(arch.getRect(), -arch.getCurrentRotation(), arch.getSweepAngle(), true, paint);
}
//logo.draw(canvas);
canvas.drawCircle(width / 2, height / 2, circle_size, paint_opaque);
logo.draw(canvas);
int textX = (int) (width / 2);
int textY = (int) ((height / 2) - ((paint_text.descent() + paint_text.ascent()) / 2));
canvas.drawText(text, textX, textY, paint_text);
invalidate();
}
There are few things wrong with your code.
You shouldn't be performing any heavy operations in the onDraw of your custom Views. That's one, really important principle of developing for android! Ideally inside your onDraw method you should ONLY draw. Sometimes you need to calculate something based on Canvas, but you should limit these sort of actions to the minimum. Everything you can preallocate and calculate somewhere else (not in onDraw), you should extract from your onDraw. In your case arch.update() (which I assume calculates the next "frame" of the animation) and calculation of your textX and textY should be moved somewhere else.
invalidate() basically means that you request for a redraw of your View. When a View is being redrawn, its onDraw will be called. That's why you really shouldn't be calling invalidate() in your onDraw! If every single onDraw requests for another onDraw, it causes a sort of an infinite loop to happen.
If you're trying to achieve a frame animation, you should be calculating all frame-related parameters in a separate thread that would wait some interval between updates, and would call invalidate() after every single one of them.
Related
I wrote an Activity which shows only one custom view.
The view is simple, draw a random color and invalidate a smaller region, and draw a random color, and invalidate a even smaller region, and so on...
The expected result should be like this. It works well by using software render, and getClipBounds() returns the region I just passed into invalidate. But when hardware acceleration is enabled, the entire view is always redrawn by a new color, and getClipBounds() return the entire view's region.
I know there are some posts like this and this. Answers said that getClipBounds() returns the entire view's region with hardware acceleration but only the ones intersecting the dirty region will be redrawn.
Is there anything wrong or my misunderstanding?
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
// random color
int color = Color.rgb((int) (Math.random() * 255),
(int) (Math.random() * 255), (int) (Math.random() * 255));
canvas.drawColor(color);
canvas.getClipBounds(rect);
// smaller dirty region
invalidate(0, 0, rect.width() - 1, rect.height() - 1);
}
Unfortunately this is a limitation of hardware acceleration in Android, at least as of Android 5. The invalidate rect is ignored and the entire view is always redrawn, requiring you to draw the entire area. If you attempt to draw only part of the view, anything else that was drawn in the view before will disappear.
I've read posts where it is claimed that Android does not re-render the whole view but only the part that changed, but this seems wrong because when I try to only render the area that was in the rect that I passed to invalidate, the rest of the view disappears. If it was true that Android only re-rendered the changed area, then I would expect the rest of the custom drawing in the view to stay visible.
iOS has much better performance with it's drawRect method and setNeedsDisplayInRect. I would have expected Android to work the same way, but alas it does not.
Im making a 2d game where my character is controlled by a joystick and I rotate him using canvas.rotate(angel, x, y). My character shoots in the same direction he is heading, now I want to add fire coming out of his rifle when he shoots. The problem is, how do I rotate this fire-image around my character?
How I rotate My character:
canvas.save();
canvas.rotate((float) controls.getAngle(), controls.charPosition.x + charBitmap.getWidth() / 2, controls.charPosition.y + charBitmap.getHeight() / 2);
character.draw(canvas, controls.charPosition.x,controls.charPosition.y);
canvas.restore();
How I rotate the Fire:
canvas.save();
canvas.rotate((float) controls.getAngle(), controls.charPosition.x + (fireBitmap.getWidth()) / 2, controls.charPosition.y + (fireBitmap.getHeight() / 2));
fire.draw(canvas, controls.charPosition.x, controls.charPosition.y);
canvas.restore();
As you probably know, drawing my fire like this will make it rotate around its own center, just like with my character. But I want it to rotate around my character so it looks like the fire is coming out of his gun.
Any ideas? If anything is unclear please let me know in a comment. Thanks!
I will try to tailor this answer so that it's more specific, but if I understand you correctly, you may not want to rotate the canvas to create the rotation of the fire. Instead you may want to describe it with a trig function relative to the character's location. So I think it will look something like your drawing of the character.
canvas.save();
canvas.rotate((float) controls.getAngle(), controls.charPosition.x + charBitmap.getWidth() / 2, controls.charPosition.y + charBitmap.getHeight() / 2);
fire.draw(canvas, controls.charPosition.x+(fireRadius*cos(fireAngle)),controls.charPosition.y+(fireRadius*sin(fireAngle));
canvas.restore();
Where in this code, fireRadius is how far from the center of the character drawing you want the fire drawing to be and fireAngle is the angle of the fire from the center of the character. This won't be quite right because it will track the corner of the fire image, not the center. I think that can be fixed somewhat easily. If not, I will change soon.
You could use Canvas.translate(dx, dy). Idea is to move the fire a certain distance away from the gun, which can be directly along x -axis, and then rotate Canvas around gun center. This results fire to rotate given angle at given distance from the gun.
canvas.save();
canvas.rotate((float) controls.getAngle(), controls.charPosition.x + (fireBitmap.getWidth()) / 2, controls.charPosition.y + (fireBitmap.getHeight() / 2));
canvas.translate(distanceFromGun, 0);
fire.draw(canvas, controls.charPosition.x, controls.charPosition.y);
canvas.restore();
Please do note the order. Canvas matrix operations are pre multiplying and though translation is made later in the code.
I know this has been discussed over and over again but I can't find a solution to suit my needs.
Scenario: To keep the explanation simple, I have a custom view which displays two images a big one for the background and a smaller one as a Wheel. The user can rotate/scale the background image with onTouch events. He also can rotate the Wheel image to make some operations. Everything is done on a custom View not SurfaceView because I need it to be transparent.
The problem: With onDraw() I always need to check what Rotation/Scale has the background image, scale/rotate it and then draw it. If the background image is smaller, let's say 512x512 the Wheel image rotation is fine. If the background image is bigger, 1280x1707, the wheel image rotation is laggy. So my guess is, manipulation and rotation of a big image in background, for each onDraw() gives me performance issues, when basically the background image should be redrawn only the the user manipulates it.
The rotation is done in something like:
canvas.save();
float dx = (maxX + minX) / 2;
float dy = (maxY + minY) / 2;
drawable.setBounds((int) minX, (int) minY, (int) maxX, (int) maxY);
canvas.translate(dx, dy);
canvas.rotate(angle * 180.0f / (float) Math.PI);
canvas.translate(-dx, -dy);
drawable.draw(canvas);
canvas.restore();
Possible solutions: I could make a new custom View which could only draw the background image and on top of it, put my current View and send touch events, when the case to my background image view. This will allow me to redraw the background image only when needed. Any other ideas ?
I was having similar performance problems and the solution I found is what I described here. Similar to what you already suggested, basically the background is only drawn once and the custom ImageView handles all transformations on its touch events.
I am experimenting with 2D graphics in Android during my off time, and I'm intrigued by the idea of creating a sprite based "sandbox" for playing around. I've looked around online and found some good tutorials, but I'm stuck with a fairly basic problem: My sprite moves faster than the terrain and "glides" over it. Also, he slowly outpaces the terrain scrolling and moves to the edge of the view.
I've got an animated sprite that I want to move around the world. I do so by changing his absolute coordinates(setting X and Y position in an 'update()' function and applying a scalar multiple to speed up or slow down the rate at which he's moving around.
this.setXPos(currX + (speed * dx2));
this.setYPos(currY + (speed * dy2));
Underneath that sprite, I'm drawing "terrain" from a bitmap. I want to continue to move that sprite around via the coordinate accessors above, but also move my view and scroll the terrain so that the sprite stays in the same relative screen location but moves through the "world". I have an imperfect implementation where player is my sprite and field is my terrain:
#Override
protected void onDraw(Canvas canvas)
{
player.updateLocation(GameValues.speedScale);
field.update(new Point(player.getXPos(), player.getYPos()));
field.draw(canvas);
player.draw(canvas);
//more stuff here...
}
And field.update() looks like(Warning: Hard-coded scariness):
public void update(Point pt)
{
sourceRect.left = pt.x - 240;
sourceRect.right = pt.x + 240;
sourceRect.top = pt.y - 400;
sourceRect.bottom = pt.y + 400;
}
The thinking there was that I would eventually just get screen dimensions and make it less 'hack-y', but get something together quickly. This could easily be where my issue is coming from. Of immediate interest is field.draw():
#Override
public void draw(Canvas canvas)
{
try
{
canvas.drawBitmap(fieldSheet, sourceRect, destRect, null);
}
catch(Exception e)
{
//Handle Exception...
}
}
You'll notice I'm using the overload of drawBitmap() that accepts a source and destination Rect and that the field.update() method moves that sourceRect to match the movement of the sprite. How can I keep the "camera (so to speak)" centered on the sprite and scroll the terrain appropriately? I had thought that moving just the sourceRect and maintaining a constant destRect would do so, but now I'm thinking I have to move the destRect around the "world" with the sprite, while maintaining the same dimensions.
Is there a better (read functional) way of making this work? I'm coming here somewhat shamefully, since I think this should be somewhat easier than it seems to be for me. Any and all help or suggestions are appreciated. Thanks!
*Edit:*Does it make sense to also move the destination Rect at the same speed as the sprite? I think I conflated the source and destination Rect's and left the destRect immobile. I'll update with the results after I get a chance to try it (maybe during lunch).
*Edit_2:*Changing the destination rectangle didn't get me there, but using the View.scrollBy(x, y) method gets me close to totally satisfied. The remaining question to be satisfied is how to "clip" the View scrolling to a rectangle that represents the "field". I believe that the View.getLeft() and View.getTop() functions, offset by the screen width and height, can be used to specify a Rect that can be virtually moved around within the constraints of the "world" and block further deltas from being argued to the View.scrollBy() method. The reason I look toward this approach is because the View doesn't seem to be positioned in absolute space, and a View.getLeft() call, even after a View.scrollBy(x, y) where x > 0, returns a 0.
I've seen a few people ask how to zoom an entire ViewGroup (such as a RelativeLayout) in one go. At the moment this is something I need to achieve. The most obvious approach, to me, would be to hold the zoom scale factor as a single variable somewhere; and in each of the child Views' onDraw() methods, that scale factor would be applied to the Canvas prior to graphics being drawn.
However, before doing that, I have tried to be clever (ha - usually a bad idea) and extend RelativeLayout, into a class called ZoomableRelativeLayout. My idea is that any scale transformation could be applied just once to the Canvas in the overridden dispatchDraw() function, so that there would be absolutely no need to separately apply the zoom in any of the child views.
Here's what I did in my ZoomableRelativeLayout. It's just a simple extension of RelativeLayout, with dispatchDraw() being overridden:
protected void dispatchDraw(Canvas canvas){
canvas.save(Canvas.MATRIX_SAVE_FLAG);
canvas.scale(mScaleFactor, mScaleFactor);
super.dispatchDraw(canvas);
canvas.restore();
}
The mScaleFactor is manipulated by a ScaleListener in the same class.
It does actually work. I can pinch to zoom the ZoomableRelativeLayout, and all of the views held within properly rescale together.
Except there's a problem. Some of those child views are animated, and hence I periodically call invalidate() on them. When the scale is 1, those child views are seen to redraw periodically perfectly fine. When the scale is other than 1, those animated child views are only seen to update in a portion of their viewing area - or not at all - depending on the zoom scale.
My initial thinking was that when an individual child view's invalidate() is being called, then it's possibly being redrawn individually by the system, rather than being passed a Canvas from the parent RelativeLayout's dispatchDraw(), meaning that the child view ends up refreshing itself without the zoom scale applied. But oddly, the elements of the child views that are redrawn on the screen are to the correct zoom scale. It's almost as if the area that the system decides to actually update in the backing bitmap remains unscaled - if that makes sense. To put it another way, if I have a single animated child View and I gradually zoom in further and further from an initial scale of 1, and if we place an imaginary box on the area where that child view is when the zoom scale is 1, then the calls to invalidate() only cause a refresh of the graphics in that imaginary box. But the graphics that are seen to update are being done to the right scale. If you zoom in so far that the child view has now moved completely away from where it was with a scale of 1, then no part of it at all is seen to refresh. I'll give another example: imagine my child view is a ball that animates by switching between yellow and red. If I zoom in a little bit such that the ball moves to the right and down, at a certain point you'll just see the top-left quarter of the ball animate colours.
If I continuously zoom in and out, I see the child views animate properly and entirely. This is because the entire ViewGroup is being redrawn.
I hope this makes sense; I've tried to explain as best as I can. Am I on a bit of a loser with my zoomable ViewGroup strategy? Is there another way?
Thanks,
Trev
If you are applying a scale factor to the drawing of your children, you also need to apply the appropriate scale factor to all of the other interactions with them -- dispatching touch events, invalidates, etc.
So in addition to dispatchDraw(), you will need to override and appropriate adjust the behavior of at least these other methods. To take care of invalidates, you will need to override this method to adjust the child coordinates appropriately:
http://developer.android.com/reference/android/view/ViewGroup.html#invalidateChildInParent(int[], android.graphics.Rect)
If you want the user to be able to interact with the child views you will also need to override this to adjust touch coordinates appropriately before they are dispatched to the children:
http://developer.android.com/reference/android/view/ViewGroup.html#dispatchTouchEvent(android.view.MotionEvent)
Also I would strongly recommend you implement this all inside of a simple ViewGroup subclass that has a single child view it manages. This will get rid of any complexity of behavior that RelativeLayout is introducing in its own ViewGroup, simplifying what you need to deal with and debug in your own code. Put the RelativeLayout as a child of your special zooming ViewGroup.
Finally, one improvement to your code -- in dispatchDraw() you want to save the canvas state after applying the scaling factor. This ensures that the child can't modify the transformation you have set.
The excellent answer from hackbod has reminded me that I need to post up the solution that I eventually came to. Please note that this solution, which worked for me for the application I was doing at the time, could be further improved with hackbod's suggestions. In particular I didn't need to handle touch events, and until reading hackbod's post it did not occur to me that if I did then I would need to scale those as well.
To recap, for my application I what I needed to achieve was to have a large diagram (specifically, the floor layout of a building) with other small "marker" symbols superimposed upon it. The background diagram and foreground symbols are all drawn using vector graphics (that is, Path() and Paint() objects applied to Canvas in the onDraw() method). The reason for wanting to create all the graphics this way, as opposed to just using bitmap resources, is because the graphics are converted at run-time using my SVG image converter.
The requirement was that the diagram and associated marker symbols would all be children of a ViewGroup, and could all be pinch-zoomed together.
A lot of the code looks messy (it was a rush job for a demonstration) so rather than just copying it all in, instead I'll try to just explain how I did it with the relevant bits of code quoted.
First of all, I have a ZoomableRelativeLayout.
public class ZoomableRelativeLayout extends RelativeLayout { ...
This class includes listener classes that extend ScaleGestureDetector and SimpleGestureListener so that the layout can be panned and zoomed. Of particular interest here is the scale gesture listener, which sets a scale factor variable and then calls invalidate() and requestLayout(). I'm not strictly certain at the moment if invalidate() is necessary, but anyway - here it is:
private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
#Override
public boolean onScale(ScaleGestureDetector detector){
mScaleFactor *= detector.getScaleFactor();
// Apply limits to the zoom scale factor:
mScaleFactor = Math.max(0.6f, Math.min(mScaleFactor, 1.5f);
invalidate();
requestLayout();
return true;
}
}
The next thing I had to do in my ZoomableRelativeLayout was to override onLayout(). To do this I found it useful to look at other people's attempts at a zoomable layout, and also I found it very useful to look at the original Android source code for RelativeLayout. My overridden method copies much of what's in RelativeLayout's onLayout() but with some modifications.
#Override
protected void onLayout(boolean changed, int l, int t, int r, int b)
{
int count = getChildCount();
for(int i=0;i<count;i++){
View child = getChildAt(i);
if(child.getVisibility()!=GONE){
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)child.getLayoutParams();
child.layout(
(int)(params.leftMargin * mScaleFactor),
(int)(params.topMargin * mScaleFactor),
(int)((params.leftMargin + child.getMeasuredWidth()) * mScaleFactor),
(int)((params.topMargin + child.getMeasuredHeight()) * mScaleFactor)
);
}
}
}
What's significant here is that when calling 'layout()' on all the children, I'm applying the scale factor to the layout parameters as well for those children. This is one step towards solving the clipping problem, and also it importantly correctly sets the x,y position of the children relative to each other for different scale factors.
A further key thing is that I am no longer attempting to scale the Canvas in dispatchDraw(). Instead each child View scales its Canvas after obtaining the scale factor from the parent ZoomableRelativeLayout via a getter method.
Next, I shall move onto what I had to do within the child Views of my ZoomableRelativeLayout. There's only one type of View I contain as children in my ZoomableRelativeLayout; it's a View for drawing SVG graphics that I call SVGView. Of course the SVG stuff is not relevant here. Here's its onMeasure() method:
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
float parentScale = ((FloorPlanLayout)getParent()).getScaleFactor();
int chosenWidth, chosenHeight;
if( parentScale > 1.0f){
chosenWidth = (int) ( parentScale * (float)svgImage.getDocumentWidth() );
chosenHeight = (int) ( parentScale * (float)svgImage.getDocumentHeight() );
}
else{
chosenWidth = (int) ( (float)svgImage.getDocumentWidth() );
chosenHeight = (int) ( (float)svgImage.getDocumentHeight() );
}
setMeasuredDimension(chosenWidth, chosenHeight);
}
And the onDraw():
#Override
protected void onDraw(Canvas canvas){
canvas.save(Canvas.MATRIX_SAVE_FLAG);
canvas.scale(((FloorPlanLayout)getParent()).getScaleFactor(),
((FloorPlanLayout)getParent()).getScaleFactor());
if( null==bm || bm.isRecycled() ){
bm = Bitmap.createBitmap(
getMeasuredWidth(),
getMeasuredHeight(),
Bitmap.Config.ARGB_8888);
... Canvas draw operations go here ...
}
Paint drawPaint = new Paint();
drawPaint.setAntiAlias(true);
drawPaint.setFilterBitmap(true);
// Check again that bm isn't null, because sometimes we seem to get
// android.graphics.Canvas.throwIfRecycled exception sometimes even though bitmap should
// have been drawn above. I'm guessing at the moment that this *might* happen when zooming into
// the house layout quite far and the system decides not to draw anything to the bitmap because
// a particular child View is out of viewing / clipping bounds - not sure.
if( bm != null){
canvas.drawBitmap(bm, 0f, 0f, drawPaint );
}
canvas.restore();
}
Again - as a disclaimer, there are probably some warts in what I have posted there and I am yet to carefully go through hackbod's suggestions and incorporate them. I intend to come back and edit this further. In the meantime, I hope it can start to provide useful pointers to others on how to implement a zoomable ViewGroup.