如何在 android 中从不同形状的位图中剪切一个圆。
我试过这段代码,但有些图像被拉伸(stretch)了:
public Bitmap getRoundedShape(Bitmap scaleBitmapImage) {
int targetWidth = 240;
int targetHeight = 200;
Bitmap targetBitmap = Bitmap.createBitmap(targetWidth,
targetHeight,Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(targetBitmap);
Path path = new Path();
path.addCircle(((float) targetWidth - 1) / 2,
((float) targetHeight - 1) / 2,
(Math.min(((float) targetWidth),
((float) targetHeight)) / 2),
Path.Direction.CCW);
canvas.clipPath(path);
Bitmap sourceBitmap = scaleBitmapImage;
canvas.drawBitmap(sourceBitmap,new Rect(0, 0, sourceBitmap.getWidth(),
sourceBitmap.getHeight()),
new Rect(0, 0, targetWidth, targetHeight), null);
return targetBitmap;
}
最佳答案
如果要对图像进行圆形切割,则需要找到以图像为中心的最大正方形。考虑到这一点,以下行解决了您的拉伸(stretch)问题:
Bitmap bitmap = ThumbnailUtils.extractThumbnail(bitmap, radius, radius, ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
此方法创建目标位图的圆形切割:
private Bitmap getCircularBitmap(int radius, Bitmap bitmap) {
Bitmap.Config conf = Bitmap.Config.ARGB_8888;
Bitmap bmp = Bitmap.createBitmap(radius, radius, conf);
Canvas canvas = new Canvas(bmp);
// creates a centered bitmap of the desired size
bitmap = ThumbnailUtils.extractThumbnail(bitmap, radius, radius, ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
BitmapShader shader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setShader(shader);
RectF rect = new RectF(0, 0, radius, radius);
canvas.drawRoundRect(rect, radius, radius, paint);
return bmp;
}
关于java - 如何在android中从不同形状的位图中切出一个圆圈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29221769/