Joe S Joe S - 18 days ago 6
Android Question

android - image alignment fault

My program is animating an imageView. This image should be in the very center of the screen. The problem is, that the image isn't in the center at all. I tried to do it with

if (x<0) {
x = this.getWidth()/2;
y = this.getHeight()/2;
}


but the program doesn't give the favored result. is it the wrong way to center it, or what's wrong?

public class AnimatedView extends ImageView{

private Context mContext;
int x = -1;
int y = -1;
private int xVelocity = 10;
private int yVelocity = 5;
private Handler h;
private final int FRAME_RATE = 30;
boolean continueAnimation = true;
private ImageView imageView;


private BitmapDrawable ball;
public AnimatedView(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
h = new Handler();
imageView = (ImageView) findViewById(R.id.imageview1);


}

private Runnable r = new Runnable() {
@Override
public void run() {
if(continueAnimation) {
invalidate();
}
}
};

protected void onDraw(Canvas c) {

ball = (BitmapDrawable) mContext.getResources().getDrawable(R.drawable.ballrot);
if (x<0) {
x = this.getWidth()/2;
y = this.getHeight()/2;
}

else {
x += xVelocity;

if ((x > this.getWidth() - ball.getBitmap().getWidth()) || (x < 0)) {
boolean continueAnimation = false;
}
}

c.drawBitmap(ball.getBitmap(), x, y, null);

if(continueAnimation)
{
h.postDelayed(r, FRAME_RATE);
}

else {
x = this.getWidth()-ball.getBitmap().getWidth();
}

}
}

Answer

To calculate center position programmatically you need to know the size of the object to be centered and container where the object reside.

centerx = container.getWidth()/2 - obj.getWidth()/2;
centery = container.getHeight()/2 - obj.getHeight()/2;

With assumption that you use top left position of object

Comments