簡體   English   中英

嘗試使用java android canvas.drawImage鏡像圖片

[英]Trying to mirror a picture with java android canvas.drawImage

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

這是我的代碼:

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();   
}

誰知道我做錯了什么?

非常感謝幫助

以下將為您服務。 我發現它本身就在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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM