Android位图:中心裁剪+创建位图圆

时间:2014-11-01 21:40:37

标签: java android bitmap

我希望能够将矩形图像中心裁剪成圆形。我设法做到了,但我确定有更有效的方法吗?这是我的代码:

中心裁剪:

    int sourceWidth = source.getWidth();
    int sourceHeight = source.getHeight();

    // Compute the scaling factors to fit the new height and width, respectively.
    // To cover the final image, the final scaling will be the bigger
    // of these two.

    int newWidth = 300;
    int newHeight  = 300;

    float xScale = (float) newWidth / sourceWidth;
    float yScale = (float) newHeight / sourceHeight;
    float scale = Math.max(xScale, yScale);

    // Now get the size of the source bitmap when scaled
    float scaledWidth = scale * sourceWidth;
    float scaledHeight = scale * sourceHeight;

    // Let's find out the upper left coordinates if the scaled bitmap
    // should be centered in the new size give by the parameters
    float left = (newWidth - scaledWidth) / 2;
    float top = (newHeight - scaledHeight) / 2;

    // The target rectangle for the new, scaled version of the source bitmap will now
    // be
    RectF targetRect = new RectF(left, top, left + scaledWidth, top + scaledHeight);

    // Finally, we create a new bitmap of the specified size and draw our new,
    // scaled bitmap onto it.
    Bitmap dest = Bitmap.createBitmap(newWidth, newHeight, source.getConfig());
   Canvas canvas = new Canvas(dest);
    canvas.drawBitmap(source, null, targetRect, null);

一旦我创建了这个新的中心裁剪的Bitmap,我现在想让它成为循环。我将上面的位图传递给这个方法:

    public Bitmap getRoundedBitmap(Bitmap bitmap) {
    final Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
    final Canvas canvas = new Canvas(output);

    final int color = Color.RED;
    final Paint paint = new Paint();
    final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
    final RectF rectF = new RectF(rect);

    paint.setAntiAlias(true);
    canvas.drawARGB(0, 0, 0, 0);
    paint.setColor(color);
    canvas.drawOval(rectF, paint);
    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
    canvas.drawBitmap(bitmap, rect, rect, paint);
    bitmap.recycle();
    return output;
    }

是否可以将这些方法组合在一起?我对Bitmap操作相当新。谢谢!

创建另一个位图然后在getRoundedBitmap()方法中进行操作似乎是不必要的。

1 个答案:

答案 0 :(得分:0)

这个答案可能对你有帮助(它显示了RoundedImageView类的代码):https://stackoverflow.com/a/16208548/1370336