主要功能在onDraw方法里面,先調(diào)用setDrawingCacheEnabled(true);讓cache可用,然后通過(guò)cache創(chuàng)建一個(gè)和原圖片一樣的圖像,通過(guò)mMatrix.preScale(1, -1);使圖片倒過(guò)來(lái),調(diào)用Bitmap.createBitmap(originalImage, 0, height/5, width, height/2, mMatrix, false);創(chuàng)建一個(gè)倒過(guò)來(lái)的圖像,調(diào)用canvas.drawBitmap(reflectionImage, 0, height/3f, null);把倒過(guò)來(lái)的圖像畫(huà)到畫(huà)布上。通過(guò)調(diào)用LinearGradient shader = new LinearGradient(0, height/2, 0,
height, 0x7fffffff, 0x0fffffff, TileMode.CLAMP);
mPaint.setShader(shader);
mPaint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));使倒影的圖像的顏色漸變,由灰色變?yōu)楹谏?/p>
時(shí)間走動(dòng)時(shí)調(diào)用buildDrawingCache();
postInvalidate();
讓倒影從新繪制。
調(diào)用setMeasuredDimension(getMeasuredWidth(), (int)(getMeasuredHeight()*1.67));設(shè)置圖像的寬度和高度。
好了,控件已經(jīng)寫(xiě)完了,現(xiàn)在只要在布局中調(diào)用這個(gè)控件就可以在Activity中顯示一個(gè)帶有倒影的時(shí)間的View了,先寫(xiě)一個(gè)布局文件:
《?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中顯示這個(gè)布局,我把這個(gè)控件的字體從新設(shè)置了一下,讓它顯示的方方正正。
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”));
}
}
運(yùn)行代碼,手機(jī)上就回顯示一個(gè)帶有倒影的時(shí)間View,時(shí)間還會(huì)走動(dòng),是不是很好玩。
好了,就到這里吧。
評(píng)論