效果以下:
java
主要代碼以下:
canvas
public static Bitmap createReflectedImage(Bitmap originalImage) { final int reflectionGap = 4; int width = originalImage.getWidth(); int height = originalImage.getHeight(); Matrix matrix = new Matrix(); matrix.preScale(1, -1); Bitmap reflectionImage = Bitmap.createBitmap(originalImage, 0, height / 2, width, height / 2, matrix, false); Bitmap bitmapWithReflection = Bitmap.createBitmap(width, (height + height / 2), Config.ARGB_8888); Canvas canvas = new Canvas(bitmapWithReflection); canvas.drawBitmap(originalImage, 0, 0, null); Paint defaultPaint = new Paint(); canvas.drawRect(0, height, width, height + reflectionGap, defaultPaint); canvas.drawBitmap(reflectionImage, 0, height + reflectionGap, null); Paint paint = new Paint(); LinearGradient shader = new LinearGradient(0, originalImage.getHeight(), 0, bitmapWithReflection.getHeight() + reflectionGap, 0×70ffffff, 0×00ffffff, TileMode.MIRROR); paint.setShader(shader); paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN)); canvas.drawRect(0, height, width, bitmapWithReflection.getHeight() + reflectionGap, paint); return bitmapWithReflection; }
解釋一下:spa
Matrix matrix = new Matrix(); matrix.preScale(1, -1);
實現圖片的反轉,見Android利用Matrix簡單處理圖片。.net
Bitmap reflectionImage = Bitmap.createBitmap(originalImage, 0, height / 2, width, height / 2, matrix, false);
建立反轉後的圖片Bitmap對象,圖片高是原圖的一半。code
Bitmap bitmapWithReflection = Bitmap.createBitmap(width, (height + height / 2), Config.ARGB_8888);
建立標準的Bitmap對象,寬和原圖一致,高是原圖的1.5倍。對象
Canvas canvas = new Canvas(bitmapWithReflection); canvas.drawBitmap(originalImage, 0, 0, null);
建立畫布對象,將原圖畫於畫布,起點是原點位置。blog
Paint defaultPaint = new Paint(); canvas.drawRect(0, height, width, height + reflectionGap, defaultPaint); canvas.drawBitmap(reflectionImage, 0, height + reflectionGap, null);
將反轉後的圖片畫到畫布中。圖片
LinearGradient shader = new LinearGradient(0, originalImage.getHeight(), 0, bitmapWithReflection.getHeight() + reflectionGap, 0×70ffffff, 0×00ffffff,
建立線性漸變LinearGradient 對象。ip
canvas.drawRect(0, height, width, bitmapWithReflection.getHeight() + reflectionGap, paint);
畫布畫出反轉圖片大小區域,而後把漸變效果加到其中,就出現了圖片的倒影效果。get