android中關于點擊屏幕,實現破碎的效果的實現

jopen 9年前發布 | 29K 次閱讀 Android Android開發 移動開發

 基本思路:

   1. 自定義一個View,用于展示這個破碎的的效果

   2.在activity中加入這個view,通過setContentView(view);

   3.注意要把activity的theme設置成 android:theme="@android:style/Theme.Translucent.NoTitleBar"  ,這樣玩起來會更有效果。

   

   

 首先重寫一個view,我們就叫CustomeView吧。自己隨便定義就好。

  定義構造函數 如下:

   

public CustomView(Context context, AttributeSet attrs) {

  super(context);

  this.setKeepScreenOn(true);

  this.setFocusable(true);

  this.setLongClickable(true);

  this.mSoundPool = new SoundPool(5, AudioManager.STREAM_SYSTEM, 5);

  this.mSoundMap.put(1, mSoundPool.load(context, R.raw.cfokwowbfv, 1));

  this.mBitmap = BitmapFactory.decodeResource(getResources(),

    R.drawable.screen);

  mXPointList = new ArrayList<Float>();

  mYPointList = new ArrayList<Float>(); 

 }


在這里聲明了一個聲音池(用于點擊屏幕時,發出破碎的逼真效果),一個bitmap,用于顯示屏幕破碎

在就是兩個list分別是mXPointList 和mYPointList,用于保存點擊時x和y的點。


接著,我們看一下OntouchEvent()

 @Override

 public boolean onTouchEvent(MotionEvent arg1) {

  // TODO Auto-generated method stub

  switch (arg1.getAction()) {

  case MotionEvent.ACTION_DOWN:

   playSound();//發聲

   mXPointList.add(arg1.getX());

   mYPointList.add(arg1.getY());

   postInvalidate();//刷新界面

   mCount++;//點擊的個數,其中,mLength是總個數

   if (mCount > mLength) {

    mXPointList.remove(0);

    mYPointList.remove(0);

    mLength++;

   }

   break;

  case MotionEvent.ACTION_UP:

   break;

  case MotionEvent.ACTION_MOVE:

   break;

  default:

   break;

  }

  return super.onTouchEvent(arg1);

 }


大家可以參照我寫的注釋,一看就明白

最后是onDraw()方法,此方法尤為重要。

 @Override

 protected void onDraw(Canvas canvas) {

  super.onDraw(canvas);

  for (int i = 0; i < mXPointList.size(); ++i) {//點了多少次,就把破碎的圖片顯示多少次

   canvas.drawBitmap(mBitmap, mXPointList.get(i) - mBitmap.getWidth()

     / 2, mYPointList.get(i) - mBitmap.getHeight() / 2, null);

  }

 }


然后在要引用的activity中的oncreate方法中進行如下設置:


@Override

 protected void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);

  CustomView view = new CustomView(this, null);

        setContentView(view);


 }



另外,不要忘了在mainfest文件中加上

 <activity

            android:name=".ScreenCrashMainActivity"

            android:theme="@android:style/Theme.Translucent.NoTitleBar"

            android:label="@string/app_name" >


來自:http://blog.csdn.net/haorantiangang/article/details/43987965

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!