首先表明一下哈,我這個人呢,平時特別喜歡斗圖,不管是微信還是QQ還是我的相冊,都會有大量的表情包,其中有一個呢讓我產生了用代碼實現它的想法,沒錯,就是這個——綠帽子!(其實當時是想把里面做成某個小伙伴,然后整蠱他一把[手動滑稽])
納尼?為什么不用PS去做一個,因為我不會PS啊,天啦嚕~~~
OK,既然要用代碼去做一個這樣的表情包(gif格式的喲),那么就要思考思路是怎樣的以及整體上如何實現:最外層用RelativeLayout,然后拋帽子和戴帽子的分別在最下面的各一邊,在拋帽子的時候add一個View,使用屬性動畫和計算好的坐標點結合貝塞爾曲線使帽子飛到戴帽子的人的頭上。OK,這就是大致的整體思路,其中一些細節性的東西可以在開發過程中慢慢補充。做之前先來看看效果圖[圖中被整蠱的對象叫什么我就不說了,打個馬賽克表示尊重],照例再丟個GitHub傳送門:GitHub傳送門
當然,也可以是這樣的,只要稍微處理一下, 就可以做一個漂亮的表情包去整蠱你的小伙伴了:
具體實現流程和相關代碼:
新建一個類GreenCapView繼承自RelativeLayout,再然后把一些基礎的工作完成。
/**
* 添加戴帽子的人,位于左下角
*/
LayoutParams layoutParams = new LayoutParams(mLuoNiMaWidth, mLuoNiMaWidth);
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
addPeopleView(R.mipmap.icon_biaoqingbao, layoutParams);
/**
* 添加拋帽子的人,位于右下角
*/
LayoutParams layoutParams2 = new LayoutParams(mLuoNiMaWidth, mLuoNiMaWidth);
layoutParams2.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
layoutParams2.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
addPeopleView(R.mipmap.people_start, layoutParams2);
下面就是初始化帽子的開始坐標和終點坐標(終點坐標是動態變化的,所以這里需要一個常量值來定義帽子摞起來之后的間隔距離),還有圖中有個“啪”的顯示動畫不知道大家注意到沒,這里也要初始化一下它的顯示坐標,定義為mPaX、mPaY。
/**
* 初始化帽子的起點坐標
*/
mStartX = ScreenUtils.getScreenWidth(mContext)
- mLuoNiMaWidth
+ 15;
mStartY = ScreenUtils.getScreenHeight(mContext)
- ScreenUtils.getStatusHeight(mContext)//狀態欄的高度
- ScreenUtils.dip2px(mContext, 55) //title的高度
- mGreenCapHeight//綠帽子的高度
- mLuoNiMaWidth;//拋帽子小人的高度
/**
* 初始化帽子的終點坐標
*/
endX = (mLuoNiMaWidth - mGreenCapWidth) / 2;
endY = ScreenUtils.getScreenHeight(mContext)
- ScreenUtils.getStatusHeight(mContext)//狀態欄的高度
- ScreenUtils.dip2px(mContext, 55) //title的高度
- mGreenCapHeight//綠帽子的高度
- mLuoNiMaWidth//拋帽子小人的高度
+ mIntervalLength//抵消第一個帽子減去的高度
+ 40;//戴帽子效果
/**
* 初始化“啪”的坐標
*/
mPaX = ScreenUtils.getScreenWidth(mContext) - ScreenUtils.dip2px(mContext, 30);
mPaY = mStartY - 50;
接下來就是在點擊屏幕的時候添加一個綠帽子然后拋到某人的頭上了,那么這里就要重寫onTouchEvent方法:
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_UP:
startAnimation();
default:
break;
}
return true;
}
在startAnimation方法里,我們需要做的就是先獲得一個綠帽子,然后執行屬性動畫,同時再執行那個“啪”字的顯示,來增強滑稽感~
/**
* 開始動畫
*/
private void startAnimation() {
endY = endY - mIntervalLength;
/**
* 判斷如果已經達到邊界,則不進行addView
*/
if (endY <= 0) {
return;
}
View mViewGood = getCap();
listGreenView.add(mViewGood);
addView(mViewGood);
getGreenCapValueAnimator(mViewGood).start();
/**
* 顯示啪字動畫
*/
if (mTextAnimationOver) {
startAnimationText();
}
}
這里最主要的不是添加綠帽子,而是綠帽子如何以瀟灑的姿勢飛到某人的頭上,那么這里就要結合貝塞爾曲線自定義一個插值器了:
/**
* 自定義貝塞爾插值器
*/
class BezierEvaluator implements TypeEvaluator<PointF> {
private PointF pointF;
/**
* 控制點坐標
*/
public BezierEvaluator(PointF pointF) {
this.pointF = pointF;
}
@Override
public PointF evaluate(float time, PointF startValue, PointF endValue) {
float timeOn = 1.0f - time;
PointF point = new PointF();
//二階貝塞爾公式
point.x = timeOn * timeOn * (startValue.x)
+ 2 * timeOn * time * (pointF.x)
+ time * time * (endValue.x);
point.y = timeOn * timeOn * (startValue.y)
+ 2 * timeOn * time * (pointF.y)
+ time * time * (endValue.y);
return point;
}
}
接下來就是給綠帽子添加屬性動畫的時候使用這個插值器:
/**
* 獲得一個綠帽子動畫
*/
private ValueAnimator getGreenCapValueAnimator(final View mViewGood) {
ValueAnimator animator = ValueAnimator.ofObject(new BezierEvaluator(new PointF(300, 300))
, new PointF(mStartX, mStartY), new PointF(endX, endY));
animator.setDuration(800);
animator.setInterpolator(new AccelerateInterpolator());
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
PointF pointF = (PointF) valueAnimator.getAnimatedValue();
mViewGood.setX(pointF.x);
mViewGood.setY(pointF.y);
}
});
return animator;
}
“啪”字動畫:
/**
* "啪"字動畫
*/
private void startAnimationText() {
mTextAnimationOver = false;
final TextView textView = new TextView(mContext);
textView.setText("啪");
textView.setTextColor(Color.parseColor("#333333"));
textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.text_size_18sp));
textView.setX(mPaX);
textView.setY(mPaY);
addView(textView);
AnimatorSet animatorSet = new AnimatorSet();
animatorSet.playTogether(ObjectAnimator.ofFloat(textView, "ScaleX", 0f, 1.0f)
, ObjectAnimator.ofFloat(textView, "ScaleY", 0f, 1.0f));
animatorSet.setDuration(500);
animatorSet.setInterpolator(new OvershootInterpolator());
animatorSet.start();
animatorSet.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
removeView(textView);
mTextAnimationOver = true;
}
});
}
不知道細心的你有沒有發現listGreenView這個變量是干嘛的,用來存儲綠帽子View的一個集合,為了后面可以把這些綠帽子remove掉。
/**
* 初始化部分參數和remove不要的view
*/
public void removeAllGreenCaps() {
for (int i = 0; i < listGreenView.size(); i++) {
if (listGreenView.get(i) != null) {
removeView(listGreenView.get(i));
}
}
listGreenView.clear();
/**
* 重新計算終點坐標
*/
endY = ScreenUtils.getScreenHeight(mContext)
- ScreenUtils.getStatusHeight(mContext)//狀態欄的高度
- ScreenUtils.dip2px(mContext, 55) //title的高度
- mGreenCapHeight//綠帽子的高度
- mLuoNiMaWidth//拋帽子小人的高度
+ mIntervalLength//抵消第一個帽子減去的高度
+ 40;//戴帽子效果
}
當然這里面還有自動模式開關的相關代碼,我就不一一貼上來了,大家有興趣的可以看下面的全家福,或者去github里下載整個項目,別忘記給小弟我一個star,你的star是我不竭的寫作動力!?。?/p>
全家福:
GreenCapView.java
public class GreenCapView extends RelativeLayout {
/**
* 上下文
*/
private Context mContext;
/**
* 起點坐標
*/
private float mStartX, mStartY;
/**
* 終點坐標(可動態改變)
*/
private float endX, endY;
/**
* 羅尼瑪的寬高、拋帽子的人的寬高
*/
private int mLuoNiMaWidth = 250;
/**
* 帽子的寬度
*/
private int mGreenCapWidth = 150;
/**
* 帽子的高度
*/
private int mGreenCapHeight = 100;
/**
* 綠帽子疊起之后的間隔長度
*/
private int mIntervalLength = 38;//40像素;
/**
* 綠帽子集合
*/
List<View> listGreenView = new ArrayList<>();
/**
* 字“啪”的顯示坐標
*/
private float mPaX, mPaY;
public GreenCapView(Context context) {
this(context, null);
}
public GreenCapView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public GreenCapView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mContext = context;
initView();
}
/**
* 添加初始化view
*
* @param resource
* @param params
*/
private void addPeopleView(int resource, ViewGroup.LayoutParams params) {
ImageView mViewMMP = new ImageView(mContext);
mViewMMP.setImageResource(resource);
mViewMMP.setLayoutParams(params);
addView(mViewMMP);
}
/**
* 初始化參數
*/
private void initView() {
setBackgroundColor(Color.WHITE);
/**
* 添加戴帽子的人,位于左下角
*/
LayoutParams layoutParams = new LayoutParams(mLuoNiMaWidth, mLuoNiMaWidth);
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
addPeopleView(R.mipmap.icon_biaoqingbao, layoutParams);
/**
* 添加拋帽子的人,位于右下角
*/
LayoutParams layoutParams2 = new LayoutParams(mLuoNiMaWidth, mLuoNiMaWidth);
layoutParams2.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
layoutParams2.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
addPeopleView(R.mipmap.people_start, layoutParams2);
/**
* 初始化帽子的起點坐標
*/
mStartX = ScreenUtils.getScreenWidth(mContext)
- mLuoNiMaWidth
+ 15;
mStartY = ScreenUtils.getScreenHeight(mContext)
- ScreenUtils.getStatusHeight(mContext)//狀態欄的高度
- ScreenUtils.dip2px(mContext, 55) //title的高度
- mGreenCapHeight//綠帽子的高度
- mLuoNiMaWidth;//拋帽子小人的高度
/**
* 初始化帽子的終點坐標
*/
endX = (mLuoNiMaWidth - mGreenCapWidth) / 2;
endY = ScreenUtils.getScreenHeight(mContext)
- ScreenUtils.getStatusHeight(mContext)//狀態欄的高度
- ScreenUtils.dip2px(mContext, 55) //title的高度
- mGreenCapHeight//綠帽子的高度
- mLuoNiMaWidth//拋帽子小人的高度
+ mIntervalLength//抵消第一個帽子減去的高度
+ 40;//戴帽子效果
/**
* 初始化“啪”的坐標
*/
mPaX = ScreenUtils.getScreenWidth(mContext) - ScreenUtils.dip2px(mContext, 30);
mPaY = mStartY - 50;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_UP:
startAnimation();
default:
break;
}
return true;
}
/**
* 開始動畫
*/
private void startAnimation() {
endY = endY - mIntervalLength;
/**
* 判斷如果已經達到邊界,則不進行addView
*/
if (endY <= 0) {
return;
}
View mViewGood = getCap();
listGreenView.add(mViewGood);
addView(mViewGood);
getGreenCapValueAnimator(mViewGood).start();
/**
* 顯示啪字動畫
*/
if (mTextAnimationOver) {
startAnimationText();
}
}
/**
* "啪"字動畫是否結束標記,作用是防止字體重合
*/
private boolean mTextAnimationOver = true;
/**
* "啪"字動畫
*/
private void startAnimationText() {
mTextAnimationOver = false;
final TextView textView = new TextView(mContext);
textView.setText("啪");
textView.setTextColor(Color.parseColor("#333333"));
textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.text_size_18sp));
textView.setX(mPaX);
textView.setY(mPaY);
addView(textView);
AnimatorSet animatorSet = new AnimatorSet();
animatorSet.playTogether(ObjectAnimator.ofFloat(textView, "ScaleX", 0f, 1.0f)
, ObjectAnimator.ofFloat(textView, "ScaleY", 0f, 1.0f));
animatorSet.setDuration(500);
animatorSet.setInterpolator(new OvershootInterpolator());
animatorSet.start();
animatorSet.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
removeView(textView);
mTextAnimationOver = true;
}
});
}
/**
* 獲得一個綠帽子
*/
private View getCap() {
final View mViewGood = new View(mContext);
mViewGood.setBackgroundResource(R.mipmap.icon_greencap);
mViewGood.setLayoutParams(new ViewGroup.LayoutParams(mGreenCapWidth, mGreenCapHeight));
return mViewGood;
}
/**
* 獲得一個綠帽子動畫
*/
private ValueAnimator getGreenCapValueAnimator(final View mViewGood) {
ValueAnimator animator = ValueAnimator.ofObject(new BezierEvaluator(new PointF(300, 300))
, new PointF(mStartX, mStartY), new PointF(endX, endY));
animator.setDuration(800);
animator.setInterpolator(new AccelerateInterpolator());
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
PointF pointF = (PointF) valueAnimator.getAnimatedValue();
mViewGood.setX(pointF.x);
mViewGood.setY(pointF.y);
}
});
return animator;
}
/**
* 初始化部分參數和remove不要的view
*/
public void removeAllGreenCaps() {
for (int i = 0; i < listGreenView.size(); i++) {
if (listGreenView.get(i) != null) {
removeView(listGreenView.get(i));
}
}
listGreenView.clear();
/**
* 重新計算終點坐標
*/
endY = ScreenUtils.getScreenHeight(mContext)
- ScreenUtils.getStatusHeight(mContext)//狀態欄的高度
- ScreenUtils.dip2px(mContext, 55) //title的高度
- mGreenCapHeight//綠帽子的高度
- mLuoNiMaWidth//拋帽子小人的高度
+ mIntervalLength//抵消第一個帽子減去的高度
+ 40;//戴帽子效果
}
/**
* 帽子飛起動畫
*/
private ValueAnimator valueAnimator;
/**
* 自動模式默認關閉
*/
private boolean mAutomaticPatternStatus = false;
public boolean ismAutomaticPatternStatus() {
return mAutomaticPatternStatus;
}
/**
* 自動模式控制開關
*/
public void automaticPatternSwitch() {
if (mAutomaticPatternStatus) {
mAutomaticPatternStatus = false;
closeAutomaticPattern();
} else {
mAutomaticPatternStatus = true;
openAutomaticPattern();
}
}
/**
* 開啟自動模式
*/
private void openAutomaticPattern() {
if (valueAnimator != null) {
valueAnimator.cancel();
valueAnimator = null;
}
valueAnimator = ValueAnimator.ofFloat(0, 1);
valueAnimator.setDuration(150);
valueAnimator.setRepeatCount(ValueAnimator.INFINITE);
valueAnimator.setRepeatMode(ValueAnimator.RESTART);
valueAnimator.setInterpolator(new LinearInterpolator());
valueAnimator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationRepeat(Animator animation) {
super.onAnimationRepeat(animation);
Log.i("TAG動畫", "動畫開始再次執行了");
startAnimation();
}
@Override
public void onAnimationStart(Animator animation) {
super.onAnimationStart(animation);
Log.i("TAG動畫", "動畫開始執行了哦哦");
startAnimation();
}
@Override
public void onAnimationCancel(Animator animation) {
super.onAnimationCancel(animation);
Log.i("TAG動畫", "動畫取消");
}
});
valueAnimator.start();
}
/**
* 關閉自動模式
*/
private void closeAutomaticPattern() {
if (valueAnimator != null) {
valueAnimator.cancel();
valueAnimator = null;
}
}
/**
* 自定義貝塞爾插值器
*/
class BezierEvaluator implements TypeEvaluator<PointF> {
private PointF pointF;
/**
* 控制點坐標
*/
public BezierEvaluator(PointF pointF) {
this.pointF = pointF;
}
@Override
public PointF evaluate(float time, PointF startValue, PointF endValue) {
float timeOn = 1.0f - time;
PointF point = new PointF();
//二階貝塞爾公式
point.x = timeOn * timeOn * (startValue.x)
+ 2 * timeOn * time * (pointF.x)
+ time * time * (endValue.x);
point.y = timeOn * timeOn * (startValue.y)
+ 2 * timeOn * time * (pointF.y)
+ time * time * (endValue.y);
return point;
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:orientation="vertical">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="55dp"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="@style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<com.zhuyong.greencapview.GreenCapView
android:id="@+id/green_cap_view_luonima"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
</com.zhuyong.greencapview.GreenCapView>
</LinearLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
private Toolbar mToolbar;
private GreenCapView mGreenCapView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Toolbar
mToolbar = (Toolbar) findViewById(R.id.toolbar);
mGreenCapView = (GreenCapView) findViewById(R.id.green_cap_view_luonima);
setSupportActionBar(mToolbar);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_luonima, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_automatic_pattern:
mGreenCapView.automaticPatternSwitch();
boolean status = mGreenCapView.ismAutomaticPatternStatus();
item.setTitle(status ? "關閉自動模式" : "打開自動模式");
break;
case R.id.action_clear:
mGreenCapView.removeAllGreenCaps();
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
}
GitHub傳送門:源碼