• 欢迎访问风的记忆博客网站,如有疑问请加作者QQ或者微信联系。作者QQ:524100248,微信号:sendtion。

Android实现View平移动画的方式

Android sendtion 5年前 (2019-01-22) 3484次浏览 已收录 0个评论 扫描二维码

1、TranslateAnimation

平移动画,大概是我们最容易想到的实现方式,但并非能满足所有需求。这种方式不能控制进度,设置好动画持续时间后,就会一直到结束。

  int screenWidth = ScreenUtils.getScreenWidth();//获取屏幕宽度
  Animation translateAnimation = new TranslateAnimation(0, screenWidth - 50, 0, 0);//设置平移的起点和终点
  translateAnimation.setDuration(10000);//动画持续的时间为 10s
  translateAnimation.setFillEnabled(true);//使其可以填充效果从而不回到原地
  translateAnimation.setFillAfter(true);//不回到起始位置
  //如果不添加 setFillEnabled 和 setFillAfter 则动画执行结束后会自动回到远点
  translateAnimation.setAnimationListener(this);
  mEvaluateProgress.setAnimation(translateAnimation);//给 imageView 添加的动画效果
  translateAnimation.startNow();//动画开始执行 放在最后即可

2、通过 drawBitmap

通过 drawBitmap 在不同的位置画出图片,适合图片作为平移动画的需求。经测试,使用 Matrix 方式对部分待透明度以及过大的图片无法绘制,通过计算位置直接绘制正常。

  Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.icon_risk_scan_line);
  int width = ScreenUtils.getScreenWidth() - bitmap.getWidth();
  //int height = bitmap.getHeight();
  //绘制原图
  //canvas.drawBitmap(bitmap, 0, 0, paint);
  canvas.drawBitmap(bitmap, progress * width / 100, 0, null);
  //平移图片
  Matrix matrix = new Matrix();
  matrix.postTranslate(progress * width / 100, height);
  canvas.drawBitmap(bitmap, matrix, null);

3、改变 View 长度

改变长度和改变位置是一个道理。获取 View 的位置,然后通过进度计算出 View 的宽度,再通过 setLayoutParams 改变 View 大小。这个方式满足我们的需求,采用的此方式。

  private void setViewLocation(int progress) {
      BitmapDrawable drawable = (BitmapDrawable) mEvaluateImage.getDrawable();
      int width = ScreenUtils.getScreenWidth();
      RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) mLayoutScan.getLayoutParams();
      layoutParams.width = width * progress / 100 + drawable.getBitmap().getWidth();
      layoutParams.height = LinearLayout.LayoutParams.MATCH_PARENT;
      mLayoutScan.setLayoutParams(layoutParams);
  }

以上。如有错误,欢迎指正!


风的记忆 , 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Android 实现 View 平移动画的方式
喜欢 (3)
[sendtion@126.com]
分享 (0)
sendtion
关于作者:
一个不断奋斗追逐梦想的少年~
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址