【问题标题】:Generating rotated bitmaps without resizing生成旋转位图而不调整大小
【发布时间】:2013-01-04 21:28:49
【问题描述】:

我正在尝试从一个图像的 20 个副本中构建一个环,这是整个环的 1/20 切片。我生成的位图是将原始图像旋转到正确的度数。原始图像是一个 130x130 的正方形

生成旋转切片的代码如下所示:

Bitmap bmp = BitmapFactory.decodeResource(context.getResources(), R.drawable.battery_green);
    FileOutputStream fos;
    for(int i = 0; i < 20; i++) {
        String idName = "batt_s_"+i;
        Matrix m = new Matrix();
        m.setRotate((i * 18)-8, bmp.getWidth()/2, bmp.getHeight()/2);

        Bitmap newBmp = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), m, true);
        try {
            fos = context.openFileOutput(idName+"_"+color+".png", Context.MODE_WORLD_READABLE);
            newBmp.compress(CompressFormat.PNG, 100, fos);
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        m.reset();
        BattConfigureSmall.saveInitPref(context, true);
    }

这些生成的位图最终插入的 ImageView 在其 XML 中都有 scaleType="center"。但是,生成的输出如下所示:

不完全是完美的戒指。如果旋转正确,切片本身会形成完美的环,因为在 API 级别 11 及更高级别中,我在这些 ImageView 上使用 android:rotate XML 属性,但我还需要支持 API 级别 7-10,所以可以有人给我一些建议吗?谢谢。

【问题讨论】:

  • 使用图像而不是画弧线有什么特别的原因吗?这对我来说似乎更容易。
  • 我有一点发光效果,就创意控制而言,我通常更喜欢使用图像文件。更不用说我已经在 Android 3.x 及更高版本上完成了所有工作。

标签: android matrix bitmap rotation


【解决方案1】:

在这种情况下,不要将矩阵与createBitmap 一起使用,我认为它会在图像大小方面做一些奇怪的事情。相反,创建一个新的 BitmapCanvas 然后用矩阵绘制到它:

Bitmap bmp = BitmapFactory.decodeResource(context.getResources(), R.drawable.battery_green);
FileOutputStream fos;
Paint paint = new Paint();
paint.setAntiAlias(true);
Matrix m = new Matrix();

for(int i = 0; i < 20; i++) {
    String idName = "batt_s_"+i;
    m.setRotate((i * 18)-8, bmp.getWidth()/2, bmp.getHeight()/2);

    Bitmap newBmp = Bitmap.createBitmap(bmp.getWidth(), bmp.getHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(newBmp);
    canvas.drawBitmap(bmp, m, paint);

    try {
        fos = context.openFileOutput(idName+"_"+color+".png", Context.MODE_WORLD_READABLE);
        newBmp.compress(CompressFormat.PNG, 100, fos);
        fos.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    m.reset();
    BattConfigureSmall.saveInitPref(context, true);
}

【讨论】:

  • drawBitmap的第一个参数应该是newBmp而不是bmp吗?因为 newBmp 是被压缩到文件中的位图。和相关问题,您的方法是否仍然打算实际写入文件?
  • 不,bmp 是正确的。您想将旧位图(但由m 转换)绘制到新位图上。我添加的代码不会写入文件,您已经拥有的代码 (newBmp.compress) 已经这样做了。试一试,看看它是否适合你(我试过了,它适合我)。
  • 我该死的,这看起来好多了。圆形本身是完美的。唯一的问题是旋转后的图像看起来非常参差不齐。有没有办法让画布抗锯齿?
  • 是的,您可以使用Paint.setAntiAlias(true),也可以使用Paint.setDither(true)。我会更新,你看看有没有帮助。
  • 它似乎没有做任何事情,setDither 也没有。看起来还不错,比以前好多了,而且这种方法仅适用于 Android 2.3 及以下用户,所以除非您有任何其他防止锯齿状的想法,否则我肯定会接受您的回答
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-11
  • 2017-08-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多