主要功能在onDraw方法里面,先調用setDrawingCacheEnabled(true);讓cache可用,然后通過cache創建一個和原圖片一樣的圖像,通過mMatrix.preScale(1, -1);使圖片倒過來,調用Bitmap.createBitmap(originalImage, 0, height/5, width, height/2, mMatrix, false);創建一個倒過來的圖像,調用canvas.drawBitmap(reflectionImage, 0, height/3f, null);把倒過來的圖像畫到畫布上。通過調用LinearGradient shader = new LinearGradient(0, height/2, 0,
height, 0x7fffffff, 0x0fffffff, TileMode.CLAMP);
mPaint.setShader(shader);
mPaint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));使倒影的圖像的顏色漸變,由灰色變為黑色。
時間走動時調用buildDrawingCache();
postInvalidate();
讓倒影從新繪制。
調用setMeasuredDimension(getMeasuredWidth(), (int)(getMeasuredHeight()*1.67));設置圖像的寬度和高度。
好了,控件已經寫完了,現在只要在布局中調用這個控件就可以在Activity中顯示一個帶有倒影的時間的View了,先寫一個布局文件:
《?xml version=“1.0” encoding=“utf-8”?》
《RelativeLayout xmlns:android=“http://schemas.android.com/apk/res/android”
android:layout_width=“match_parent”
android:layout_height=“match_parent”
android:background=“#000000”
android:paddingTop=“@dimen/activity_vertical_margin” 》
《com.alex.reflecttextview.ReflectTextView
android:id=“@+id/timeView”
android:textSize=“@dimen/reflect_size”
android:layout_width=“match_parent”
android:layout_height=“wrap_content”
android:layout_alignParentBottom=“true”
android:gravity=“top|center_horizontal” /》
《/RelativeLayout》
然后在Activity中顯示這個布局,我把這個控件的字體從新設置了一下,讓它顯示的方方正正。
package com.alex.reflecttextview;
import android.app.Activity;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Window win = getWindow();
win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
| WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
| WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
setContentView(R.layout.activity_main);
TimeView tv = (TimeView) findViewById(R.id.timeView);
tv.setTypeface(Typeface.createFromAsset(getAssets(), “fonts/DS-DIGII.TTF”));
}
}
運行代碼,手機上就回顯示一個帶有倒影的時間View,時間還會走動,是不是很好玩。
好了,就到這里吧。
評論