在Android画布上旋转RectF

时间:2014-10-16 22:04:12

标签: android canvas

我一直在寻找,似乎无法找到解决方法。我正在尝试显示一个枪(作为一个RectF),它在画布上的空间中,使用tick方法自动旋转。我正在保存画布,用枪角旋转它,然后绘制矩形,然后在刻度方法内恢复画布......但它只旋转一次枪。有人知道如何让它连续旋转吗?谢谢!


如果有人在寻找类似的东西,可以在下面的评论中回答这个问题。

    public class SpaceAnimator implements Animator {

// constants
private static final int FRAME_INTERVAL = 60; // animation-frame interval, in milliseconds
private static final int BACKGROUND_COLOR = Color.BLACK; // background color

// paint objects
private Paint whitePaint;
private Paint yellowPaint;
private Paint bluePaint;

//random number generator
Random randomGen = new Random();

//PointF array to hold star positions 
ArrayList<PointF> stars = new ArrayList<PointF>();

//Number of stars
int numberOfStars = 100;

//PointFs for center of the sun and angle of gun
PointF centerOfSun1 = new PointF(300,200);
float angleOfGun = 1;


// constructor
public SpaceAnimator() {

    //Create a white paint object
    whitePaint = new Paint();
    whitePaint.setColor(Color.WHITE);

    //Create a yellow paint object
    yellowPaint = new Paint();
    yellowPaint.setColor(Color.YELLOW); 

    //create a blue paint object
    bluePaint = new Paint();
    bluePaint.setColor(Color.BLUE);

    //Set position of the stars
    for(int i = 0; i < numberOfStars; i++)
    {
        int randStarX = randomGen.nextInt(100); //random X initial position
        int randStarY = randomGen.nextInt(100); //random Y initial position
        stars.add(new PointF(randStarX, randStarY)); //set X and Y positions
    }

}

/**
 * Interval between animation frames
 * 
 * @return the time interval between frames, in milliseconds.
 */
public int interval() {
    return FRAME_INTERVAL;
}

/**
 * The background color.
 * 
 * @return the background color onto which we will draw the image.
 */
public int backgroundColor() {
    // create/return the background color
    return BACKGROUND_COLOR;
}

/**
 * Action to perform on clock tick
 * 
 * @param g the canvas object on which to draw
 */
public void tick(Canvas g) {

    int height = g.getHeight();
    int width = g.getWidth();

    //draw the stars
    for(int i = 0; i < numberOfStars; i++)
    {
        g.drawCircle(stars.get(i).x/100 * width, stars.get(i).y/100 * height, randomGen.nextInt(2), whitePaint);
    }

    //draw the first sun
    g.drawCircle(centerOfSun1.x, centerOfSun1.y, 40, yellowPaint);

    //rotate/draw the gun
    g.save();
    g.rotate(angleOfGun);
    g.drawRect(new RectF(width/2 - 20, height/2 - 20, width/2 + 20, height/2 + 20), bluePaint);
    g.restore();
}

1 个答案:

答案 0 :(得分:0)

您发布的代码中没有任何内容正在递增(或递减)angleOfGun。

如果这是真的,那么你只会&#34;看到&#34;它第一次旋转1度然后粘在那里。您需要在tick方法的末尾添加这样的行:

angleOfGun = (angleOfGun + 1) % 360;