我需要将图像从圆形更改为普通正方形。
我是编程方面的新手, 我在此代码中停留了2天,有人知道如何更改吗?
我已经尝试了一切,但无法解决
我对画布一无所知,我已经研究过解决此问题的方法,但是我仍然无法做到
public static Bitmap getCircleBitmap(Bitmap bitmap) {
final int scaledWidth = 100;
final int scaledHeight = 100;
bitmap = Bitmap.createScaledBitmap(bitmap, scaledWidth, scaledHeight, true);
Bitmap output;
Rect srcRect, dstRect;
float r;
final int width = bitmap.getWidth();
final int height = bitmap.getHeight();
if (width > height) {
output = Bitmap.createBitmap(height, height, Bitmap.Config.ARGB_8888);
int left = (width - height) / 2;
int right = left + height;
srcRect = new Rect(left, 0, right, height);
dstRect = new Rect(0, 0, height, height);
r = height / 2;
} else {
output = Bitmap.createBitmap(width, width, Bitmap.Config.ARGB_8888);
int top = (height - width) / 2;
int bottom = top + width;
srcRect = new Rect(0, top, width, bottom);
dstRect = new Rect(0, 0, width, width);
r = width / 2;
}
Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Paint paint = new Paint();
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawCircle(r, r, r, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(bitmap, srcRect, dstRect, paint);
bitmap.recycle();
return output;
}
public static Bitmap getBitmapFromVectorDrawable(Context context, int drawableId) {
Drawable drawable = AppCompatResources.getDrawable(context, drawableId);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
drawable = (DrawableCompat.wrap(drawable)).mutate();
}
Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(),
drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
}
}
答案 0 :(得分:0)
如果您查看代码,则在方法 getCircleBitmap()的结尾处,您将看到以下代码行:
canvas.drawCircle(r, r, r, paint);
这就是使用DrawCircle为您绘制圆形图像的人。 您可以做的是,将其替换为DrawRect。那应该为你做那把戏。
但是,如果只需要从矢量绘制正方形图像,则可以直接使用标准的 ImageView 并将矢量用作图像资源。