딱 봐 도 좋아 하 는 loading 애니메이션 효과 Android 분석 실현
효과 적 으로 볼 때 우 리 는 다음 과 같은 몇 가지 문 제 를 고려 해 야 한다.
그 다음 에 우 리 는 효 과 를 분해 한 후에 하나씩 격파 할 것 이다.
전체 효과 에 있어 서 우리 가 필요 로 하 는 그림 은 주로 날 아 다 니 는 작은 잎 과 오른쪽 에서 회전 하 는 선풍기 이다.다른 부분 은 모두 색 값 으로 그 릴 수 있다.물론 우 리 는 편 의 를 위해 바닥 틀 까지 함께 잘 랐 다.
먼저 gif 그림 에서 날 아 다 니 는 작은 잎 과 오른쪽 회전 하 는 선풍기,밑부분 테 두 리 를 파 내 고 작은 잎 자 도 는 다음 과 같다.
우리 가 처리 해 야 할 것 은 주로 두 부분 이 있다.
진도 조 의 위 치 는 외부 에서 들 어 오 는 progress 에 따라 계산 하면 그림 에서 1,2,3 단계 로 나 눌 수 있다.
//mProgressWidth ,
mCurrentProgressPosition = mProgressWidth * mProgress / TOTAL_PROGRESS;
그 다음 에 위의 논리 에 따라 그립 니 다.그 중에서 위의 그림 속 의 빨간색 아크 각 도 를 계산 해 야 합 니 다.계산 방법 은 다음 과 같 습 니 다.
//
int angle = (int) Math.toDegrees(Math.acos((mArcRadius - mCurrentProgressPosition)/ (float) mArcRadius));
Math.acos() -반 코사인 함수;Math.toDegrees()-라디안 은 각도 로 전환 되 고 Math.toRadians 각 도 는 라디안 으로 전환 된다.
그래서 원호 의 시작 점 은:
int startAngle = 180 - angle;
원호 가 그 은 각 도 는:2 * angle
이 부분의 코드 는 다음 과 같다.
// mProgressWidth ,
mCurrentProgressPosition = mProgressWidth * mProgress / TOTAL_PROGRESS;
// 1
if (mCurrentProgressPosition < mArcRadius) {
Log.i(TAG, "mProgress = " + mProgress + "---mCurrentProgressPosition = "
+ mCurrentProgressPosition
+ "--mArcProgressWidth" + mArcRadius);
// 1. ARC, orange ARC
// 2.
// 1. ARC
canvas.drawArc(mArcRectF, 90, 180, false, mWhitePaint);
// 2.
mWhiteRectF.left = mArcRightLocation;
canvas.drawRect(mWhiteRectF, mWhitePaint);
// 3. ARC
//
int angle = (int) Math.toDegrees(Math.acos((mArcRadius - mCurrentProgressPosition)
/ (float) mArcRadius));
//
int startAngle = 180 - angle;
//
int sweepAngle = 2 * angle;
Log.i(TAG, "startAngle = " + startAngle);
canvas.drawArc(mArcRectF, startAngle, sweepAngle, false, mOrangePaint);
} else {
Log.i(TAG, "mProgress = " + mProgress + "---transfer-----mCurrentProgressPosition = "
+ mCurrentProgressPosition
+ "--mArcProgressWidth" + mArcRadius);
// 1. white RECT
// 2. Orange ARC
// 3. orange RECT
// 1. white RECT
mWhiteRectF.left = mCurrentProgressPosition;
canvas.drawRect(mWhiteRectF, mWhitePaint);
// 2. Orange ARC
canvas.drawArc(mArcRectF, 90, 180, false, mOrangePaint);
// 3. orange RECT
mOrangeRectF.left = mArcRightLocation;
mOrangeRectF.right = mCurrentProgressPosition;
canvas.drawRect(mOrangeRectF, mOrangePaint);
}
다음은 잎 부분 을 살 펴 보 겠 습 니 다.먼저 효과 상황 에 따라 곡선 함 수 를 대체적으로 확정 하고 표준 함수 방정식 은 y=A(wx+Q)+h 이 며 그 중에서 w 영향 주기,A 영향 진폭,주기 T=2*Math.PI/w 이다.
효과 에 따라 알 수 있 듯 이 주 기 는 대체적으로 총 진도 길이 이기 때문에 w=(float)((float)2*Math.PI/mProgressWidth)를 확인한다.
효 과 를 자세히 살 펴 보면 우 리 는 잎 이 흔 들 리 는 과정 에서 진폭 이 완전히 일치 하지 않 고 착지 효과 가 발생 한 다 는 것 을 알 수 있다.그렇다면 우 리 는 잎 에 Type 을 정의 하고 Type 에 따라 서로 다른 진폭 을 확인한다.
우 리 는 잎 사 귀 대상 을 만 듭 니 다:
private class Leaf {
//
float x, y;
//
StartType type;
//
int rotateAngle;
// --0 ,1
int rotateDirection;
// (ms)
long startTime;
}
유형 은 매 거 진 정 의 를 사용 하 는데 사실은 서로 다른 진폭 을 구분 하 는 데 쓰 인 다.
private enum StartType {
LITTLE, MIDDLE, BIG
}
하나 이상 의 잎 정 보 를 만 드 는 데 사용 할 LeafFactory 클래스 를 만 듭 니 다:
private class LeafFactory {
private static final int MAX_LEAFS = 6;
Random random = new Random();
//
public Leaf generateLeaf() {
Leaf leaf = new Leaf();
int randomType = random.nextInt(3);
// -
StartType type = StartType.MIDDLE;
switch (randomType) {
case 0:
break;
case 1:
type = StartType.LITTLE;
break;
case 2:
type = StartType.BIG;
break;
default:
break;
}
leaf.type = type;
//
leaf.rotateAngle = random.nextInt(360);
// ( )
leaf.rotateDirection = random.nextInt(2);
// ,
mAddTime += random.nextInt((int) (LEAF_FLOAT_TIME * 1.5));
leaf.startTime = System.currentTimeMillis() + mAddTime;
return leaf;
}
//
public List<Leaf> generateLeafs() {
return generateLeafs(MAX_LEAFS);
}
//
public List<Leaf> generateLeafs(int leafSize) {
List<Leaf> leafs = new LinkedList<Leaf>();
for (int i = 0; i < leafSize; i++) {
leafs.add(generateLeaf());
}
return leafs;
}
}
두 개의 상 량 을 각각 중간 진폭 과 사이 의 진폭 차 를 기록 하도록 정의 합 니 다.
//
private static final int MIDDLE_AMPLITUDE = 13;
//
private static final int AMPLITUDE_DISPARITY = 5;
[html] view plain copy CODE
//
private int mMiddleAmplitude = MIDDLE_AMPLITUDE;
//
private int mAmplitudeDisparity = AMPLITUDE_DISPARITY;
이상 의 정보 가 있 으 면 우 리 는 잎의 Y 값 을 얻 을 수 있 습 니 다.
// Y
private int getLocationY(Leaf leaf) {
// y = A(wx+Q)+h
float w = (float) ((float) 2 * Math.PI / mProgressWidth);
float a = mMiddleAmplitude;
switch (leaf.type) {
case LITTLE:
// = -
a = mMiddleAmplitude - mAmplitudeDisparity;
break;
case MIDDLE:
a = mMiddleAmplitude;
break;
case BIG:
// = +
a = mMiddleAmplitude + mAmplitudeDisparity;
break;
default:
break;
}
Log.i(TAG, "---a = " + a + "---w = " + w + "--leaf.x = " + leaf.x);
return (int) (a * Math.sin(w * leaf.x)) + mArcRadius * 2 / 3;
}
다음 에 우 리 는 잎 을 그리 기 시작 했다.
/**
*
*
* @param canvas
*/
private void drawLeafs(Canvas canvas) {
long currentTime = System.currentTimeMillis();
for (int i = 0; i < mLeafInfos.size(); i++) {
Leaf leaf = mLeafInfos.get(i);
if (currentTime > leaf.startTime && leaf.startTime != 0) {
// -- (x,y)
getLeafLocation(leaf, currentTime);
//
canvas.save();
// Matrix
Matrix matrix = new Matrix();
float transX = mLeftMargin + leaf.x;
float transY = mLeftMargin + leaf.y;
Log.i(TAG, "left.x = " + leaf.x + "--leaf.y=" + leaf.y);
matrix.postTranslate(transX, transY);
// , LEAF_ROTATE_TIME
float rotateFraction = ((currentTime - leaf.startTime) % LEAF_ROTATE_TIME)
/ (float) LEAF_ROTATE_TIME;
int angle = (int) (rotateFraction * 360);
//
int rotate = leaf.rotateDirection == 0 ? angle + leaf.rotateAngle : -angle
+ leaf.rotateAngle;
matrix.postRotate(rotate, transX
+ mLeafWidth / 2, transY + mLeafHeight / 2);
canvas.drawBitmap(mLeafBitmap, matrix, mBitmapPaint);
canvas.restore();
} else {
continue;
}
}
}
마지막 으로 외부 에 몇 개의 인 터 페 이 스 를 노출 합 니 다.
/**
*
*
* @param amplitude
*/
public void setMiddleAmplitude(int amplitude) {
this.mMiddleAmplitude = amplitude;
}
/**
*
*
* @param disparity
*/
public void setMplitudeDisparity(int disparity) {
this.mAmplitudeDisparity = disparity;
}
/**
*
*
* @param amplitude
*/
public int getMiddleAmplitude() {
return mMiddleAmplitude;
}
/**
*
*
* @param disparity
*/
public int getMplitudeDisparity() {
return mAmplitudeDisparity;
}
/**
*
*
* @param progress
*/
public void setProgress(int progress) {
this.mProgress = progress;
postInvalidate();
}
/**
*
*
* @param time
*/
public void setLeafFloatTime(long time) {
this.mLeafFloatTime = time;
}
/**
*
*
* @param time
*/
public void setLeafRotateTime(long time) {
this.mLeafRotateTime = time;
이 인터페이스 들 은 무엇 에 쓰 입 니까?우리 의 동 효 를 완전히 수 동 으로 조절 할 수 있 는 것 으로 만 드 는데,이렇게 하면 무슨 좋 은 점 이 있 습 니까?1.제품 을 쏘 고 닭 을 쏘 고 습 기 를 확인 하 는 데 더욱 편리 합 니 다.YY 를 피하 고 스스로 수 동 으로 조절 합 니 다.한 번 의 변경 매개 변 수 는 설치,조회,재 수정,재 확인 하지 않 습 니 다.N 번 후에'내 가 원 하 는 것 이 아 닌 것 같 습 니 다'라 고 말 합 니 다.순간 하늘 이 무 너 지고 땅 이 어 두 워 지면 서 전 세계 에 버 림 받 은 것 같 습 니 다.
2.당신 이 전면적 이 고 생각 이 치밀 하 며 프로 그래 밍 을 잘 하고 디자인 을 잘 하 는 예술가 임 을 나타 내 는 데 편리 합 니 다.물론 이것 은 순 전 히 YY 이 고 주로 여러분 을 편리 하 게 하 는 것 입 니 다.
이렇게 되면 닭 을 쏘 는 습 기 는 끊임없이 조절 하면 실시 간 으로 보 여 주 는 효 과 를 볼 수 있 고 마지막 으로 최종 매개 변 수 를 피드백 하면 된다.만사 가 다 잘 되 고 모든 것 이 다 잘 된다.
물론 상대방 이 예 쁜 여동생 이 고 말 을 걸 기회 가 없어 서 고생 이 많 습 니 다.이상 의 내용 은 제 가 말 하지 않 았 다 고 생각 하고 요구 대로 쓰 지 않 으 면 그녀 가 먼저 찾 아 올 것 입 니 다.밥 도 거꾸로 살 지도 모른다 고...
자,본론 으로 들 어가 서 마무리 부분 을 완성 하면 우 리 는 모든 매개 변 수 를 조절 할 수 있 습 니 다.
나머지 layot 와 activity 를 붙 입 니 다:
activity:
public class LeafLoadingActivity extends Activity implements OnSeekBarChangeListener,
OnClickListener {
Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case REFRESH_PROGRESS:
if (mProgress < 40) {
mProgress += 1;
// 800ms
mHandler.sendEmptyMessageDelayed(REFRESH_PROGRESS,
new Random().nextInt(800));
mLeafLoadingView.setProgress(mProgress);
} else {
mProgress += 1;
// 1200ms
mHandler.sendEmptyMessageDelayed(REFRESH_PROGRESS,
new Random().nextInt(1200));
mLeafLoadingView.setProgress(mProgress);
}
break;
default:
break;
}
};
};
private static final int REFRESH_PROGRESS = 0x10;
private LeafLoadingView mLeafLoadingView;
private SeekBar mAmpireSeekBar;
private SeekBar mDistanceSeekBar;
private TextView mMplitudeText;
private TextView mDisparityText;
private View mFanView;
private Button mClearButton;
private int mProgress = 0;
private TextView mProgressText;
private View mAddProgress;
private SeekBar mFloatTimeSeekBar;
private SeekBar mRotateTimeSeekBar;
private TextView mFloatTimeText;
private TextView mRotateTimeText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.leaf_loading_layout);
initViews();
mHandler.sendEmptyMessageDelayed(REFRESH_PROGRESS, 3000);
}
private void initViews() {
mFanView = findViewById(R.id.fan_pic);
RotateAnimation rotateAnimation = DXAnimationUtils.initRotateAnimation(false, 1500, true,
Animation.INFINITE);
mFanView.startAnimation(rotateAnimation);
mClearButton = (Button) findViewById(R.id.clear_progress);
mClearButton.setOnClickListener(this);
mLeafLoadingView = (LeafLoadingView) findViewById(R.id.leaf_loading);
mMplitudeText = (TextView) findViewById(R.id.text_ampair);
mMplitudeText.setText(getString(R.string.current_mplitude,
mLeafLoadingView.getMiddleAmplitude()));
mDisparityText = (TextView) findViewById(R.id.text_disparity);
mDisparityText.setText(getString(R.string.current_Disparity,
mLeafLoadingView.getMplitudeDisparity()));
mAmpireSeekBar = (SeekBar) findViewById(R.id.seekBar_ampair);
mAmpireSeekBar.setOnSeekBarChangeListener(this);
mAmpireSeekBar.setProgress(mLeafLoadingView.getMiddleAmplitude());
mAmpireSeekBar.setMax(50);
mDistanceSeekBar = (SeekBar) findViewById(R.id.seekBar_distance);
mDistanceSeekBar.setOnSeekBarChangeListener(this);
mDistanceSeekBar.setProgress(mLeafLoadingView.getMplitudeDisparity());
mDistanceSeekBar.setMax(20);
mAddProgress = findViewById(R.id.add_progress);
mAddProgress.setOnClickListener(this);
mProgressText = (TextView) findViewById(R.id.text_progress);
mFloatTimeText = (TextView) findViewById(R.id.text_float_time);
mFloatTimeSeekBar = (SeekBar) findViewById(R.id.seekBar_float_time);
mFloatTimeSeekBar.setOnSeekBarChangeListener(this);
mFloatTimeSeekBar.setMax(5000);
mFloatTimeSeekBar.setProgress((int) mLeafLoadingView.getLeafFloatTime());
mFloatTimeText.setText(getResources().getString(R.string.current_float_time,
mLeafLoadingView.getLeafFloatTime()));
mRotateTimeText = (TextView) findViewById(R.id.text_rotate_time);
mRotateTimeSeekBar = (SeekBar) findViewById(R.id.seekBar_rotate_time);
mRotateTimeSeekBar.setOnSeekBarChangeListener(this);
mRotateTimeSeekBar.setMax(5000);
mRotateTimeSeekBar.setProgress((int) mLeafLoadingView.getLeafRotateTime());
mRotateTimeText.setText(getResources().getString(R.string.current_float_time,
mLeafLoadingView.getLeafRotateTime()));
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (seekBar == mAmpireSeekBar) {
mLeafLoadingView.setMiddleAmplitude(progress);
mMplitudeText.setText(getString(R.string.current_mplitude,
progress));
} else if (seekBar == mDistanceSeekBar) {
mLeafLoadingView.setMplitudeDisparity(progress);
mDisparityText.setText(getString(R.string.current_Disparity,
progress));
} else if (seekBar == mFloatTimeSeekBar) {
mLeafLoadingView.setLeafFloatTime(progress);
mFloatTimeText.setText(getResources().getString(R.string.current_float_time,
progress));
}
else if (seekBar == mRotateTimeSeekBar) {
mLeafLoadingView.setLeafRotateTime(progress);
mRotateTimeText.setText(getResources().getString(R.string.current_rotate_time,
progress));
}
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
@Override
public void onClick(View v) {
if (v == mClearButton) {
mLeafLoadingView.setProgress(0);
mHandler.removeCallbacksAndMessages(null);
mProgress = 0;
} else if (v == mAddProgress) {
mProgress++;
mLeafLoadingView.setProgress(mProgress);
mProgressText.setText(String.valueOf(mProgress));
}
}
}
layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#fed255"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="100dp"
android:text="loading ..."
android:textColor="#FFA800"
android:textSize=" 30dp" />
<RelativeLayout
android:id="@+id/leaf_content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="50dp" >
<com.baidu.batterysaverDemo.ui.LeafLoadingView
android:id="@+id/leaf_loading"
android:layout_width="302dp"
android:layout_height="61dp"
android:layout_centerHorizontal="true" />
<ImageView
android:id="@+id/fan_pic"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="35dp"
android:src="@drawable/fengshan" />
</RelativeLayout>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:id="@+id/seek_content_one"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:layout_marginTop="15dp" >
<TextView
android:id="@+id/text_ampair"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:textColor="#ffffa800"
android:textSize="15dp" />
<SeekBar
android:id="@+id/seekBar_ampair"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_weight="1" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:layout_marginTop="15dp"
android:orientation="horizontal" >
<TextView
android:id="@+id/text_disparity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:textColor="#ffffa800"
android:textSize="15dp" />
<SeekBar
android:id="@+id/seekBar_distance"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_weight="1" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:layout_marginTop="15dp"
android:orientation="horizontal" >
<TextView
android:id="@+id/text_float_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:textColor="#ffffa800"
android:textSize="15dp" />
<SeekBar
android:id="@+id/seekBar_float_time"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_weight="1" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:layout_marginTop="15dp"
android:orientation="horizontal" >
<TextView
android:id="@+id/text_rotate_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:textColor="#ffffa800"
android:textSize="15dp" />
<SeekBar
android:id="@+id/seekBar_rotate_time"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_weight="1" />
</LinearLayout>
<Button
android:id="@+id/clear_progress"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:text=" , "
android:textSize="18dp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:layout_marginTop="15dp"
android:orientation="horizontal" >
<Button
android:id="@+id/add_progress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" : "
android:textSize="18dp" />
<TextView
android:id="@+id/text_progress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:textColor="#ffffa800"
android:textSize="15dp" />
</LinearLayout>
</LinearLayout>
</ScrollView>
</LinearLayout>
최종 효 과 는 다음 과 같 습 니 다.원래 20+s 를 녹 음 했 지만 PS 는 5s 만 돌 릴 수 있 으 니 관심 있 는 분 들 은 직접 실행 하 셔 서 하 세 요.이상 은 본문의 전체 내용 이 므 로 여러분 의 학습 에 도움 이 되 기 를 바 랍 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
vue+element 기반 전역loading 프로세스 상세 설명프로젝트에서 사용하는 것은 vue+element가 실현하는 전역loading 1. 필요한 구성 요소 도입, 여기는 주로router와element 구성 요소, element 구성 요소 도입은 element 홈페이지를 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.