生成旋转的位图而不调整大小

时间:2013-01-04 21:28:49

标签: android matrix bitmap rotation

我正在尝试从单个图像的20个副本构建一个环,这是完整环的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及以上我在这些ImageViews上使用android:rotate XML属性,但我也需要支持API级别7-10,所以可以有人给我一些建议吗?谢谢。

1 个答案:

答案 0 :(得分: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);
}
相关问题