自定義view 製造水波紋的效果
要自定義View可以創一個新的class去繼承View這個類,
之後針對需要定義一些自己要的功能,
這裡提供一個類似水波紋效果的code。
之後針對需要定義一些自己要的功能,
這裡提供一個類似水波紋效果的code。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
}; | |
} |
留言
張貼留言