4.28

安卓自定义 View 与动画实现
自定义 View 和动画能显著提升应用的用户体验,以下是 Java 实现的核心技术:

  1. 自定义 View 基础
    java
    public class CustomView extends View {
    private Paint paint;
    private Path path;

    public CustomView(Context context) {
    super(context);
    init();
    }

    public CustomView(Context context, AttributeSet attrs) {
    super(context, attrs);
    init();
    }

    private void init() {
    paint = new Paint();
    paint.setColor(Color.RED);
    paint.setStyle(Paint.Style.FILL);
    path = new Path();
    }

    @Override
    protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    int width = getWidth();
    int height = getHeight();

     path.moveTo(width/2, 0);
     path.lineTo(width, height);
     path.lineTo(0, height);
     path.close();
     
     canvas.drawPath(path, paint);
    

    }
    }

  2. 属性动画实现
    java
    ObjectAnimator animator = ObjectAnimator.ofFloat(view, "translationY", 0f, 200f);
    animator.setDuration(1000);
    animator.setInterpolator(new AccelerateDecelerateInterpolator());
    animator.setRepeatCount(ObjectAnimator.INFINITE);
    animator.setRepeatMode(ObjectAnimator.REVERSE);
    animator.start();

  3. 组合动画
    java
    AnimatorSet set = new AnimatorSet();
    ObjectAnimator scaleX = ObjectAnimator.ofFloat(view, "scaleX", 1f, 1.5f);
    ObjectAnimator scaleY = ObjectAnimator.ofFloat(view, "scaleY", 1f, 1.5f);
    ObjectAnimator alpha = ObjectAnimator.ofFloat(view, "alpha", 1f, 0.5f);

set.play(scaleX).with(scaleY).before(alpha);
set.setDuration(1000);
set.start();

posted @ 2025-04-28 21:01  Echosssss  阅读(12)  评论(0)    收藏  举报