【问题标题】:Android Bitmap: Center Cropping + Creating a Circle of the BitmapAndroid位图:中心裁剪+创建位图圆圈
【发布时间】:2014-11-02 06:59:10
【问题描述】:

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

中心裁剪:

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

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

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

是否可以将这些方法结合在一起?我对位图操作相当陌生。谢谢!

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

【问题讨论】:

    标签: java android bitmap


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2011-10-18
      • 1970-01-01
      • 2017-07-05
      • 2020-01-31
      • 2015-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-08
      相关资源
      最近更新 更多