1

我设法使用 ObjectAnimator 为布局上的视图设置动画。

我尝试使用 ObjectAnimator 类在画布上为对象设置动画,但没有成功。有可能吗?

我所做的是创建一个扩展视图的类,我像在布局上一样定义了 ObjectAnimator,然后我在画布上绘制它并开始动画(objectanimator.start)

这是代码:(//行是我的布局尝试女巫工作)

public class MainActivity extends Activity {

SurfaceClass surface;
private ObjectAnimator anima;
//private Button but;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    surface = new SurfaceClass(this);
    surface.resume();
    setContentView(surface);
    //but = (Button)findViewById(R.id.button1);
    //anima = ObjectAnimator.ofFloat(but, "y",400);
    //anima.setDuration(5000);
    //anima.setRepeatCount(100);
    //anima.setRepeatMode(1);
    //anima.start();

}

表面:

public class SurfaceClass extends SurfaceView implements Runnable{

SurfaceHolder sHolder;
Boolean isRunning;
Thread th;
Canvas c;
Obj object;
ObjectAnimator anima;


public SurfaceClass(Context context) {
    super(context);
    // TODO Auto-generated constructor stub
    anima = ObjectAnimator.ofFloat(object, "y",1f);
    anima.setDuration(3000);
    anima.setRepeatCount(100);
    anima.setRepeatMode(1);
    //anima.start();
    object = new Obj(context);
    sHolder = getHolder();
    isRunning = false;
}

@Override
public void run() {
    // TODO Auto-generated method stub
    while(isRunning){
        if(!sHolder.getSurface().isValid())
            continue;
        c = sHolder.lockCanvas();
        synchronized(sHolder){
            doDraw(c);
        }
        sHolder.unlockCanvasAndPost(c);
    }
}

private void doDraw(Canvas c) {
    // TODO Auto-generated method stub

    c.drawBitmap(object.pic, object.x, object.y, null);
    anima.start();
}

public void resume() {
    // TODO Auto-generated method stub
    isRunning = true;
    th = new Thread(this);
    th.start();
}

}

目的:

public class Obj extends View {
float x = 200,y=30;
Bitmap pic;

public Obj(Context context) {
    super(context);
    // TODO Auto-generated constructor stub
    pic = BitmapFactory.decodeResource(getResources(), R.drawable.cat_trance);
}
public void setY(float f){
    y=f;
}
public float getY(){
    return y;
}

}

4

1 回答 1

0

尝试这个,

@Override
protected void onAttachedToWindow(){
    anima.start();
}

anima.start();并在doDraw方法中删除。

于 2014-01-13T16:28:17.310 回答