2013-08-26 76 views
0

我在嘗試用java android canvas.drawImage旋轉圖片時出現問題。我正在做一個小遊戲,並使用drawImage函數在屏幕上繪製不同的圖片。但是現在我想旋轉一些小圖片,我爲此創建了一個名爲drawMirroredImage的函數。但是現在這些小圖像不會出現在同一個地方。試圖用java鏡像一張圖片android canvas.drawImage

這裏是我的代碼:

public void drawImage(Image Image, int x, int y) { 
    canvas.drawBitmap(((AndroidImage) Image).bitmap, x, y, null); 
} 

public void drawMirroredImage(Image Image, int x, int y) { 
    canvas.save(); 
    canvas.scale(-1.0f, 1.0f); 
    canvas.drawBitmap(((AndroidImage) Image).bitmap, x - canvas.getWidth(), y, null); 
    canvas.restore(); 
} 

任何人都知道我在做什麼錯?

感謝您的幫助

+0

您是否試圖顯示該圖像的反射......? –

+0

是的普魯,這就是我想要的> _ < – user2204353

回答

2

以下將爲您工作。 我發現它在SO本身的某個地方,但不記得在哪裏。

public static Bitmap getReflectionedBitmap(Context context,int resourceId,Bitmap originalImage,int reflectionGap) { 

     if(originalImage==null) 
     originalImage = BitmapFactory.decodeResource(context.getResources(),resourceId); 

     int width = originalImage.getWidth(); 
     int height = originalImage.getHeight(); 

     // This will not scale but will flip on the Y axis 
     Matrix matrix = new Matrix(); 
     matrix.preScale(1, -1); 
     // Create a Bitmap with the flip matix applied to it. 
     // We only want the bottom half of the image 
     Bitmap reflectionImage = Bitmap.createBitmap(originalImage, 0, 
       height/2, width, height/2, matrix, false); 

     // Create a new bitmap with same width but taller to fit reflection 

     Bitmap bitmapWithReflection = Bitmap.createBitmap(width, 
       (height + height/2), Config.ARGB_8888); 
     // Create a new Canvas with the bitmap that's big enough for 
     // the image plus gap plus reflection 

     Canvas canvas = new Canvas(bitmapWithReflection); 
     // Draw in the original image 
     canvas.drawBitmap(originalImage, 0, 0, null); 
     // Draw in the gap 
     Paint deafaultPaint = new Paint(); 
     deafaultPaint.setColor(0xffffffff); 
     canvas.drawRect(0, height, width, height + reflectionGap , deafaultPaint); 

     canvas.drawBitmap(reflectionImage, 0, height + reflectionGap, null); 

     Paint paint = new Paint(); 
     LinearGradient shader = new LinearGradient(0, 
       originalImage.getHeight(), 0, bitmapWithReflection.getHeight() 
         + reflectionGap, 0x70ffffff, 0x00ffffff, TileMode.CLAMP); 
     // Set the paint to use this shader (linear gradient) 
     paint.setShader(shader); 
     // Set the Transfer mode to be porter duff and destination in 
     paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN)); 
     canvas.drawRect(0, height, width, bitmapWithReflection.getHeight() 
       + reflectionGap, paint); 

     return bitmapWithReflection; 
    } 

我調整了一小段代碼片段,將它與資源圖片一起使用。

如果要爲資源中的圖像創建反射,請將null作爲參數代替Bitmap