android - 在不调整大小的情况下生成旋转位图

标签 android matrix bitmap rotation

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

original slice

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

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

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

enter image description here

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

最佳答案

对于这种情况,不要将矩阵与 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);
}

关于android - 在不调整大小的情况下生成旋转位图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14165277/

相关文章:

button - Android 弹出窗口不会关闭

python - numpy 将 RGB 图像转换为 YIQ 颜色空间

matlab - 在matlab中使用for循环更改矩阵的元素

android - 如何在没有内存不足异常的情况下从 "onPictureTaken"旋转图片?

android - 无法读/写 FIDO2 特性

java - 在 1 个请求中将多个文件从 Android 上传到 AppEngine

c++ - 在 C++ 中围绕窗口快速移动位图

java - 像 Snapchat 一样在图片中添加灰色背景的文本?安卓/Java

android - BottomNavigation 初始 setCurrentItem 不显示 fragment 并且重新启动 fragment 失败

python - 高效行标准化矩阵