【问题标题】:How to toggle flip Imageview horizontally in android如何在android中水平切换Imageview
【发布时间】:2017-03-02 15:31:02
【问题描述】:

我有一个 Imageview,我想在用户单击名为 "Flip Picture" 的按钮时水平翻转图片。并且当用户第二次单击此按钮时,它应该返回到原始状态,换句话说就是翻转回来。

所以它应该重复这种行为。我发现这个有用的代码可以在不使用外部库的情况下翻转图像视图,但不知道如何翻转:

这是代码:

 public Bitmap flipImage(Bitmap src, int type) {
    // create new matrix for transformation
    Matrix matrix = new Matrix();
    // if vertical
    if(type == FLIP_VERTICAL) {
        // y = y * -1
        matrix.preScale(1.0f, -1.0f);
    }
    // if horizonal
    else if(type == FLIP_HORIZONTAL) {
        // x = x * -1


        // unknown type
    } else {
        return null;
    }

    // return transformed image
    return Bitmap.createBitmap(src, 0, 0, src.getWidth(), src.getHeight(), matrix, true);
}

这是我尝试将其应用于名为 FlipImage 的图像视图的方式

Flipimage.setImageBitmap(flipImage(BitmapFactory.decodeResource(getResources(), R.drawable.doom01),2));

【问题讨论】:

标签: android imageview flip


【解决方案1】:

我在测试和尝试时发现了 Answer My self : 只需翻转它会翻转图像视图的值:这是这一行的魔力:

第一次点击时:

matrix.preScale(-1.0f, 1.0f);

第二次点击时:

matrix.preScale(1.0f, -1.0f);

所以你可以初始化计数器,也可以使用 android 的切换按钮。

【讨论】:

    【解决方案2】:

    这是一个很好的代码,可以帮助您解决问题。将位图图像传递给函数,函数返回位图数据类型。 ... 或download source code

    public Bitmap FlipHorizontally(Bitmap originalImage) {
            // The gap we want between the flipped image and the original image
            final int flipGap = 4;
    
    
            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 matrix applied to it.
            // We only want the bottom half of the image
            Bitmap flipImage = Bitmap.createBitmap(originalImage, 0,0 , width, height, matrix, true);
    
            // Create a new bitmap with same width but taller to fit reflection
            Bitmap bitmapWithFlip = Bitmap.createBitmap((width + width + flipGap), height, Bitmap.Config.ARGB_8888);
    
            // Create a new Canvas with the bitmap that's big enough for
            Canvas canvas = new Canvas(bitmapWithFlip);
    
            //Draw original image
            canvas.drawBitmap(originalImage, 0, 0, null);
    
           //Draw the Flipped Image
            canvas.drawBitmap(flipImage, width+flipGap, 0, null);
    
    
            return bitmapWithFlip;
        }
    

    Learn more

    【讨论】:

      猜你喜欢
      • 2019-01-25
      • 2011-02-04
      • 1970-01-01
      • 2020-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-07
      • 1970-01-01
      相关资源
      最近更新 更多