android自定義view實現圓周運動
本文實例為大傢分享瞭android自定義view實現圓周運動的具體代碼,供大傢參考,具體內容如下
思想
自定義Animation,自己定義半徑,相當於原來控件的位置為(0,0),按照每個角度區間,計算新的位置,跟著時間變動
逆時針轉動
public class VenusCircleAnimation extends Animation { private int radii; public VenusCircleAnimation(int radii) { this.radii = radii; } @Override protected void applyTransformation(float interpolatedTime, Transformation t) { //根據取值范圍 確定圓周運動的角度范圍。360-0 float d = 360 * interpolatedTime;//interpolatedTime 取值范圍 0-1,表示時間 if (d > 360) { //算法二 d = d-360; } int[] ps = getNewLocation((int) d, radii);// t.getMatrix().setTranslate(ps[0], ps[1]); } public int[] getNewLocation(int newAngle, int r) { int newAngle1; int newX = 0, newY = 0; if (newAngle >= 0 && newAngle <= 90) { // Math.PI/180得到的結果就是1°,然後再乘以角度得到角度 newX = (int) ( - (r * Math.cos(newAngle * Math.PI / 180))); newY = (int) (r * Math.sin(newAngle * Math.PI / 180)); } else if (newAngle >= 90 && newAngle <= 180) {// 90-180 newAngle1 = 180 - newAngle; newX = (int) (r * Math.cos(newAngle1 * Math.PI / 180)); newY = (int) (r * Math.sin(newAngle1 * Math.PI / 180)); } else if (newAngle >= 180 && newAngle <= 270) {//180-270 newAngle1 = 270 - newAngle; newX = (int) (r * Math.sin(newAngle1 * Math.PI / 180)); newY = (int) ( - (r * Math.cos(newAngle1 * Math.PI / 180))); } else if (newAngle >= 270) {//270-360 newAngle1 = 360 - newAngle; newX = (int) ( - (r * Math.cos(newAngle1 * Math.PI / 180))); newY = (int) ( - (r * Math.sin(newAngle1 * Math.PI / 180))); } return new int[]{newX, newY}; } }
順時針
public class CircleAnimation extends Animation { private int radii; public CircleAnimation(int radii) { this.radii = radii; } @Override protected void applyTransformation(float interpolatedTime, Transformation t) { float d = 360 * interpolatedTime ; if (d > 360) { d = d - 360; } int[] ps = getNewLocation((int) d, radii);// t.getMatrix().setTranslate(ps[0], ps[1]); } public int[] getNewLocation(int newAngle, int r) { int newAngle1; int newX = 0, newY = 0; if (newAngle >= 0 && newAngle <= 90) { newX = (int) (r * Math.sin(newAngle * Math.PI / 180)); newY = (int) ( - (r * Math.cos(newAngle * Math.PI / 180))); } else if (newAngle >= 90 && newAngle <= 180) {// 90-180 newAngle1 = 180 - newAngle; newX = (int) (r * Math.sin(newAngle1 * Math.PI / 180)); newY = (int) (r * Math.cos(newAngle1 * Math.PI / 180)); } else if (newAngle >= 180 && newAngle <= 270) {//180-270 newAngle1 = 270 - newAngle; newX = (int) ( - (r * Math.cos(newAngle1 * Math.PI / 180))); newY = (int) (r * Math.sin(newAngle1 * Math.PI / 180)); } else if (newAngle >= 270 && newAngle <= 360) {//270-360 newAngle1 = 360 - newAngle; newX = (int) ( - (r * Math.sin(newAngle1 * Math.PI / 180))); newY = (int) ( - (r * Math.cos(newAngle1 * Math.PI / 180))); } return new int[]{newX, newY}; } }
使用
CircleAnimation animationw = new CircleAnimation(m); animationw.setDuration(d); animationw.setRepeatCount(-1); animationw.setInterpolator(new LinearInterpolator()); imageView.startAnimation(animationw);
以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。