简体   繁体   English

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

[英]Android Bitmap: Center Cropping + Creating a Circle of the Bitmap

I want to be able to center-crop a rectangle image into a circle. 我希望能够将矩形图像居中裁剪为圆形。 I have managed to do it but I'm sure there's more efficient way of doing it? 我已经做到了,但是我确定有更有效的方法吗? Here's my code: 这是我的代码:

Center Crop: 中心作物:

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

Once I have created this new center-cropped Bitmap, I now want to make it circular. 创建此新的中心裁剪的位图后,现在我想使其变为圆形。 I pass the bitmap from above into this method: 我从上面将位图传递给此方法:

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

Is it possible to combine these methods together? 是否可以将这些方法结合在一起? I'm fairly new to Bitmap manipulation. 我是位图操作的新手。 Thanks! 谢谢!

Creating another bitmap then manipulating in the getRoundedBitmap() method seems to be unnecessary. 似乎不需要创建另一个位图,然后在getRoundedBitmap()方法中进行操作。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM