自定義view 製造水波紋的效果

要自定義View可以創一個新的class去繼承View這個類,

之後針對需要定義一些自己要的功能,

這裡提供一個類似水波紋效果的code。



import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import java.util.ArrayList;
import android.os.Handler;
import java.util.logging.LogRecord;
import static java.lang.StrictMath.abs;
import static java.lang.StrictMath.pow;
import static java.lang.StrictMath.sqrt;
public class MyWave extends View {
private ArrayList<Wave> wList;
Handler handler = new Handler();
int positionX=0;
int positionY=0;
public MyWave(Context context, AttributeSet attrs) {
super(context, attrs);
wList = new ArrayList<Wave>();
handler.postDelayed(callOnDraw,100);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
for (int i = 0; i < wList.size(); i++) {
Wave wave = wList.get(i);
canvas.drawCircle(wave.pointX, wave.pointY, wave.radius, wave.paint);
}
}
private class Wave {
//圓心
int pointX;
int pointY;
//畫筆
Paint paint=new Paint();
//半徑
int radius;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
super.onTouchEvent(event);
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_MOVE:
int x = (int) event.getX();
int y = (int) event.getY();
Wave temp = new Wave();
double dis = sqrt(pow((positionX-x),2)+pow((positionY-y),2));
temp.pointX = x;
temp.pointY = y;
temp.paint.setAlpha(100);
temp.radius = 0;
if(dis > 30){
wList.add(temp);
positionX = x;
positionY = y;
}
// System.out.println(x);
}
return true;
}
private Runnable callOnDraw = new Runnable() {
@Override
public void run() {
invalidate();
System.out.println(wList.size()+" size");
for(int i = 0 ;i<wList.size();i++){
wList.get(i).radius = wList.get(i).radius +10;
wList.get(i).paint.setAlpha(wList.get(i).paint.getAlpha() - 10);
if(wList.get(i).paint.getAlpha() < 5){
wList.remove(i);
i--;
}
}
handler.postDelayed(this,100);
}
};
}
view raw MyWave.java hosted with ❤ by GitHub

留言

這個網誌中的熱門文章

android service作法

android app之間使用socket做溝通

html css & bootstrap心得