首先表明一下哈,我這個(gè)人呢,平時(shí)特別喜歡斗圖,不管是微信還是QQ還是我的相冊(cè),都會(huì)有大量的表情包,其中有一個(gè)呢讓我產(chǎn)生了用代碼實(shí)現(xiàn)它的想法,沒錯(cuò),就是這個(gè)——綠帽子?。ㄆ鋵?shí)當(dāng)時(shí)是想把里面做成某個(gè)小伙伴,然后整蠱他一把[手動(dòng)滑稽])
納尼?為什么不用PS去做一個(gè),因?yàn)槲也粫?huì)PS啊,天啦嚕~~~
OK,既然要用代碼去做一個(gè)這樣的表情包(gif格式的喲),那么就要思考思路是怎樣的以及整體上如何實(shí)現(xiàn):最外層用RelativeLayout,然后拋帽子和戴帽子的分別在最下面的各一邊,在拋帽子的時(shí)候add一個(gè)View,使用屬性動(dòng)畫和計(jì)算好的坐標(biāo)點(diǎn)結(jié)合貝塞爾曲線使帽子飛到戴帽子的人的頭上。OK,這就是大致的整體思路,其中一些細(xì)節(jié)性的東西可以在開發(fā)過程中慢慢補(bǔ)充。做之前先來看看效果圖[圖中被整蠱的對(duì)象叫什么我就不說了,打個(gè)馬賽克表示尊重],照例再丟個(gè)GitHub傳送門:GitHub傳送門
當(dāng)然,也可以是這樣的,只要稍微處理一下, 就可以做一個(gè)漂亮的表情包去整蠱你的小伙伴了:
具體實(shí)現(xiàn)流程和相關(guān)代碼:
新建一個(gè)類GreenCapView繼承自RelativeLayout,再然后把一些基礎(chǔ)的工作完成。
/**
* 添加戴帽子的人,位于左下角
*/
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);
下面就是初始化帽子的開始坐標(biāo)和終點(diǎn)坐標(biāo)(終點(diǎn)坐標(biāo)是動(dòng)態(tài)變化的,所以這里需要一個(gè)常量值來定義帽子摞起來之后的間隔距離),還有圖中有個(gè)“啪”的顯示動(dòng)畫不知道大家注意到?jīng)],這里也要初始化一下它的顯示坐標(biāo),定義為mPaX、mPaY。
/**
* 初始化帽子的起點(diǎn)坐標(biāo)
*/
mStartX = ScreenUtils.getScreenWidth(mContext)
- mLuoNiMaWidth
+ 15;
mStartY = ScreenUtils.getScreenHeight(mContext)
- ScreenUtils.getStatusHeight(mContext)//狀態(tài)欄的高度
- ScreenUtils.dip2px(mContext, 55) //title的高度
- mGreenCapHeight//綠帽子的高度
- mLuoNiMaWidth;//拋帽子小人的高度
/**
* 初始化帽子的終點(diǎn)坐標(biāo)
*/
endX = (mLuoNiMaWidth - mGreenCapWidth) / 2;
endY = ScreenUtils.getScreenHeight(mContext)
- ScreenUtils.getStatusHeight(mContext)//狀態(tài)欄的高度
- ScreenUtils.dip2px(mContext, 55) //title的高度
- mGreenCapHeight//綠帽子的高度
- mLuoNiMaWidth//拋帽子小人的高度
+ mIntervalLength//抵消第一個(gè)帽子減去的高度
+ 40;//戴帽子效果
/**
* 初始化“啪”的坐標(biāo)
*/
mPaX = ScreenUtils.getScreenWidth(mContext) - ScreenUtils.dip2px(mContext, 30);
mPaY = mStartY - 50;
接下來就是在點(diǎn)擊屏幕的時(shí)候添加一個(gè)綠帽子然后拋到某人的頭上了,那么這里就要重寫onTouchEvent方法:
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_UP:
startAnimation();
default:
break;
}
return true;
}
在startAnimation方法里,我們需要做的就是先獲得一個(gè)綠帽子,然后執(zhí)行屬性動(dòng)畫,同時(shí)再執(zhí)行那個(gè)“啪”字的顯示,來增強(qiáng)滑稽感~
/**
* 開始動(dòng)畫
*/
private void startAnimation() {
endY = endY - mIntervalLength;
/**
* 判斷如果已經(jīng)達(dá)到邊界,則不進(jìn)行addView
*/
if (endY <= 0) {
return;
}
View mViewGood = getCap();
listGreenView.add(mViewGood);
addView(mViewGood);
getGreenCapValueAnimator(mViewGood).start();
/**
* 顯示啪字動(dòng)畫
*/
if (mTextAnimationOver) {
startAnimationText();
}
}
這里最主要的不是添加綠帽子,而是綠帽子如何以瀟灑的姿勢飛到某人的頭上,那么這里就要結(jié)合貝塞爾曲線自定義一個(gè)插值器了:
/**
* 自定義貝塞爾插值器
*/
class BezierEvaluator implements TypeEvaluator<PointF> {
private PointF pointF;
/**
* 控制點(diǎn)坐標(biāo)
*/
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;
}
}
接下來就是給綠帽子添加屬性動(dòng)畫的時(shí)候使用這個(gè)插值器:
/**
* 獲得一個(gè)綠帽子動(dòng)畫
*/
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;
}
“啪”字動(dòng)畫:
/**
* "啪"字動(dòng)畫
*/
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;
}
});
}
不知道細(xì)心的你有沒有發(fā)現(xiàn)listGreenView這個(gè)變量是干嘛的,用來存儲(chǔ)綠帽子View的一個(gè)集合,為了后面可以把這些綠帽子remove掉。
/**
* 初始化部分參數(shù)和remove不要的view
*/
public void removeAllGreenCaps() {
for (int i = 0; i < listGreenView.size(); i++) {
if (listGreenView.get(i) != null) {
removeView(listGreenView.get(i));
}
}
listGreenView.clear();
/**
* 重新計(jì)算終點(diǎn)坐標(biāo)
*/
endY = ScreenUtils.getScreenHeight(mContext)
- ScreenUtils.getStatusHeight(mContext)//狀態(tài)欄的高度
- ScreenUtils.dip2px(mContext, 55) //title的高度
- mGreenCapHeight//綠帽子的高度
- mLuoNiMaWidth//拋帽子小人的高度
+ mIntervalLength//抵消第一個(gè)帽子減去的高度
+ 40;//戴帽子效果
}
當(dāng)然這里面還有自動(dòng)模式開關(guān)的相關(guān)代碼,我就不一一貼上來了,大家有興趣的可以看下面的全家福,或者去github里下載整個(gè)項(xiàng)目,別忘記給小弟我一個(gè)star,你的star是我不竭的寫作動(dòng)力?。。?/p>
全家福:
GreenCapView.java
public class GreenCapView extends RelativeLayout {
/**
* 上下文
*/
private Context mContext;
/**
* 起點(diǎn)坐標(biāo)
*/
private float mStartX, mStartY;
/**
* 終點(diǎn)坐標(biāo)(可動(dòng)態(tài)改變)
*/
private float endX, endY;
/**
* 羅尼瑪?shù)膶捀摺伱弊拥娜说膶捀? */
private int mLuoNiMaWidth = 250;
/**
* 帽子的寬度
*/
private int mGreenCapWidth = 150;
/**
* 帽子的高度
*/
private int mGreenCapHeight = 100;
/**
* 綠帽子疊起之后的間隔長度
*/
private int mIntervalLength = 38;//40像素;
/**
* 綠帽子集合
*/
List<View> listGreenView = new ArrayList<>();
/**
* 字“啪”的顯示坐標(biāo)
*/
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);
}
/**
* 初始化參數(shù)
*/
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);
/**
* 初始化帽子的起點(diǎn)坐標(biāo)
*/
mStartX = ScreenUtils.getScreenWidth(mContext)
- mLuoNiMaWidth
+ 15;
mStartY = ScreenUtils.getScreenHeight(mContext)
- ScreenUtils.getStatusHeight(mContext)//狀態(tài)欄的高度
- ScreenUtils.dip2px(mContext, 55) //title的高度
- mGreenCapHeight//綠帽子的高度
- mLuoNiMaWidth;//拋帽子小人的高度
/**
* 初始化帽子的終點(diǎn)坐標(biāo)
*/
endX = (mLuoNiMaWidth - mGreenCapWidth) / 2;
endY = ScreenUtils.getScreenHeight(mContext)
- ScreenUtils.getStatusHeight(mContext)//狀態(tài)欄的高度
- ScreenUtils.dip2px(mContext, 55) //title的高度
- mGreenCapHeight//綠帽子的高度
- mLuoNiMaWidth//拋帽子小人的高度
+ mIntervalLength//抵消第一個(gè)帽子減去的高度
+ 40;//戴帽子效果
/**
* 初始化“啪”的坐標(biāo)
*/
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;
}
/**
* 開始動(dòng)畫
*/
private void startAnimation() {
endY = endY - mIntervalLength;
/**
* 判斷如果已經(jīng)達(dá)到邊界,則不進(jìn)行addView
*/
if (endY <= 0) {
return;
}
View mViewGood = getCap();
listGreenView.add(mViewGood);
addView(mViewGood);
getGreenCapValueAnimator(mViewGood).start();
/**
* 顯示啪字動(dòng)畫
*/
if (mTextAnimationOver) {
startAnimationText();
}
}
/**
* "啪"字動(dòng)畫是否結(jié)束標(biāo)記,作用是防止字體重合
*/
private boolean mTextAnimationOver = true;
/**
* "啪"字動(dòng)畫
*/
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;
}
});
}
/**
* 獲得一個(gè)綠帽子
*/
private View getCap() {
final View mViewGood = new View(mContext);
mViewGood.setBackgroundResource(R.mipmap.icon_greencap);
mViewGood.setLayoutParams(new ViewGroup.LayoutParams(mGreenCapWidth, mGreenCapHeight));
return mViewGood;
}
/**
* 獲得一個(gè)綠帽子動(dòng)畫
*/
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;
}
/**
* 初始化部分參數(shù)和remove不要的view
*/
public void removeAllGreenCaps() {
for (int i = 0; i < listGreenView.size(); i++) {
if (listGreenView.get(i) != null) {
removeView(listGreenView.get(i));
}
}
listGreenView.clear();
/**
* 重新計(jì)算終點(diǎn)坐標(biāo)
*/
endY = ScreenUtils.getScreenHeight(mContext)
- ScreenUtils.getStatusHeight(mContext)//狀態(tài)欄的高度
- ScreenUtils.dip2px(mContext, 55) //title的高度
- mGreenCapHeight//綠帽子的高度
- mLuoNiMaWidth//拋帽子小人的高度
+ mIntervalLength//抵消第一個(gè)帽子減去的高度
+ 40;//戴帽子效果
}
/**
* 帽子飛起動(dòng)畫
*/
private ValueAnimator valueAnimator;
/**
* 自動(dòng)模式默認(rèn)關(guān)閉
*/
private boolean mAutomaticPatternStatus = false;
public boolean ismAutomaticPatternStatus() {
return mAutomaticPatternStatus;
}
/**
* 自動(dòng)模式控制開關(guān)
*/
public void automaticPatternSwitch() {
if (mAutomaticPatternStatus) {
mAutomaticPatternStatus = false;
closeAutomaticPattern();
} else {
mAutomaticPatternStatus = true;
openAutomaticPattern();
}
}
/**
* 開啟自動(dòng)模式
*/
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動(dòng)畫", "動(dòng)畫開始再次執(zhí)行了");
startAnimation();
}
@Override
public void onAnimationStart(Animator animation) {
super.onAnimationStart(animation);
Log.i("TAG動(dòng)畫", "動(dòng)畫開始執(zhí)行了哦哦");
startAnimation();
}
@Override
public void onAnimationCancel(Animator animation) {
super.onAnimationCancel(animation);
Log.i("TAG動(dòng)畫", "動(dòng)畫取消");
}
});
valueAnimator.start();
}
/**
* 關(guān)閉自動(dòng)模式
*/
private void closeAutomaticPattern() {
if (valueAnimator != null) {
valueAnimator.cancel();
valueAnimator = null;
}
}
/**
* 自定義貝塞爾插值器
*/
class BezierEvaluator implements TypeEvaluator<PointF> {
private PointF pointF;
/**
* 控制點(diǎn)坐標(biāo)
*/
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 ? "關(guān)閉自動(dòng)模式" : "打開自動(dòng)模式");
break;
case R.id.action_clear:
mGreenCapView.removeAllGreenCaps();
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
}
GitHub傳送門:源碼