標籤:
這個在TV上用的挺多的, 網上很多都是對ImageView的圖片做的, 感覺不是很好, 這裡實現了一個可以對任何View做倒影的.
/** * * @className: MirrorView * @description: 對普通View做封裝, 讓這個View出現倒影效果, 注意,使用這個View之後, * 會讓原來的View的Height擴大REFHEIGHT高度, 用來顯示反射鏡面, * @author: gaoshuai * @date: 2015年8月11日 上午11:31:16 */public class MirrorView extends FrameLayout{ private View mContentView; protected boolean mHasReflection = true; private static int REFHEIGHT = -1; public static Paint RefPaint = null; private Bitmap mReflectBitmap; private Canvas mReflectCanvas; public MirrorView(Context context) { super(context); if (REFHEIGHT == -1) REFHEIGHT = 100; if (RefPaint == null) { RefPaint = new Paint(Paint.ANTI_ALIAS_FLAG); RefPaint.setShader(new LinearGradient(0, 0, 0, REFHEIGHT, new int[] { 0x77000000, 0x66AAAAAA, 0x0500000, 0x00000000 }, new float[] { 0.0f, 0.1f, 0.9f, 1.0f }, Shader.TileMode.CLAMP)); RefPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN)); } this.setClickable(true); } public void setContentView(View view) { FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); lp.bottomMargin = REFHEIGHT; mContentView = view; addView(view, lp); } public View getContentView() { return mContentView; } public void setReflection(boolean ref) { mHasReflection = ref; } @Override public boolean performClick() { return mContentView.performClick(); } @Override protected void dispatchDraw(Canvas canvas) { super.dispatchDraw(canvas); if (mHasReflection) { if (mReflectBitmap == null) { mReflectBitmap = Bitmap.createBitmap(mContentView.getWidth(), REFHEIGHT, Bitmap.Config.ARGB_8888); mReflectCanvas = new Canvas(mReflectBitmap); } drawReflection(mReflectCanvas, mContentView); //繪製這個View的反射效果 canvas.save(); int dy = mContentView.getBottom(); int dx = mContentView.getLeft(); canvas.translate(dx, dy); canvas.drawBitmap(mReflectBitmap, 0, 0, null); canvas.restore(); } } public Bitmap getReflectBitmap() { return mReflectBitmap; } public void drawReflection(Canvas canvas, View view) { canvas.save(); canvas.clipRect(0, 0, view.getWidth(), REFHEIGHT); canvas.save(); canvas.scale(1, -1); canvas.translate(0, -view.getHeight()); view.draw(canvas); canvas.restore(); canvas.drawRect(0, 0, view.getWidth(), REFHEIGHT, RefPaint); canvas.restore(); }}
測試Activity
public class MainActivity extends Activity{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); FrameLayout container = (FrameLayout) findViewById(R.id.test); MirrorView mirrorItemView = new MirrorView(this); TextView textView = new TextView(this); textView.setWidth(300); textView.setText("我就是想測試一下鏡子View"); textView.setBackgroundResource(R.drawable.ic_launcher); mirrorItemView.setContentView(textView); container.addView(mirrorItemView); }}
Android對View進行包裹, 實現鏡面發射效果