【问题标题】:How to rotate a bitmap in android when click a button?单击按钮时如何在android中旋转位图?
【发布时间】:2012-06-06 02:02:57
【问题描述】:

旋转位图时出现问题。我的要求如下,

  1. 通过相机捕获图像并将捕获的图像显示在 ImageView 中。
  2. 当我单击/触摸图像时,在图像视图上显示两个按钮。一个按钮用于顺时针(45 度)方向旋转图像,另一个按钮用于逆时针方向旋转图像。

    我在这个过程中使用了下面的代码,不幸的是它只工作一次,当我第一次点击按钮时,ti 将旋转对应于 45 度的图像,之后按钮点击没有变化。 //点击

    public void onClick(View v) {

        switch (v.getId()) {
    
        case R.id.right_image_rotate:
    
            try {
                System.gc();
                Runtime.getRuntime().gc();
                unbindDrawables(findViewById(R.id.image_viewer));
                imageRotate();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            break;
    
        case R.id.left_image_rotate:
    
            try {
                System.gc();
                Runtime.getRuntime().gc();
                unbindDrawables(findViewById(R.id.image_viewer));
                imageRotate();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            break;
        case R.id.image_viewer:
            rotateLayout.setVisibility(View.VISIBLE);
            imageLeft_rotate.setVisibility(View.VISIBLE);
            imageRight_rotate.setVisibility(View.VISIBLE);
            break;
        default:
            break;
        }
    }
    
    
    
        Bitmap bitmapOrg = BitmapFactory.decodeFile(saved_image_file
                .getAbsolutePath());
    
        int width = bitmapOrg.getWidth();
    
        int height = bitmapOrg.getHeight();
    
        int newWidth = 200;
    
        int newHeight = 200;
    
        // calculate the scale - in this case = 0.4f
    
        float scaleWidth = ((float) newWidth) / width;
    
        float scaleHeight = ((float) newHeight) / height;
    
        Matrix matrix = new Matrix();
    
        matrix.postScale(scaleWidth, scaleHeight);
        matrix.postRotate(45);
    
        Bitmap resizedBitmap = Bitmap.createBitmap(bitmapOrg, 0, 0, width,
                height, matrix, true);
    
        srcBitmap.setScaleType(ScaleType.CENTER);
        srcBitmap.setImageBitmap(resizedBitmap);
    

【问题讨论】:

  • 我们需要更多代码。你在使用 onClickListener 吗? matrix.portRotate(deg) 对于 45 度也应该可以正常工作。
  • @BradHekman:我累了,但它只工作一次。当我用拳头点击它旋转,然后我点击第二次意味着它不会旋转。
  • @gtumca-MAC:供您参考,我使用了您提到的链接中的代码。
  • 查看我发布的完整代码的第二个链接,它对我来说很好用

标签: android image


【解决方案1】:

这是因为每次单击按钮时,您仍然引用的是原始图像,而不是您更改的图像。如果您想继续旋转或修改更改后的图像,则必须引用它;不是原版。

只需创建一个全局变量并将更改的位图存储在其中。然后当按下按钮时,检查它是否为空。如果为null,则使用原来的;否则使用更改后的

【讨论】:

    猜你喜欢
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-31
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多