我有一个我在这里使用Facebook API
抓取的网址,我尝试将其更改为循环Bitmap
。这工作正常,但我的图像实际上似乎偏离中心。以下是它的外观示例:
但我无法弄清楚我的代码出错了。以下是将URL转换为循环Bitmap
:
public Bitmap getBitmapFromURL(String userId) {
try {
URL imgUrl = new URL("https://graph.facebook.com/" + userId + "/picture?type=large");
InputStream in = (InputStream) imgUrl.getContent();
Bitmap bitmap = BitmapFactory.decodeStream(in);
Bitmap output;
if (bitmap.getWidth() > bitmap.getHeight()) {
output = Bitmap.createBitmap(bitmap.getHeight(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
} else {
output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getWidth(), Bitmap.Config.ARGB_8888);
}
Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
float r = 0;
if (bitmap.getWidth() > bitmap.getHeight()) {
r = bitmap.getHeight() / 2;
} else {
r = bitmap.getWidth() / 2;
}
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, rect, rect, paint);
return output;
} catch (IOException e) {
// Log exception
return null;
}
}
答案 0 :(得分:0)
你犯了这个错误:
canvas.drawBitmap(bitmap, rect, rect, paint);
您复制的不是基本图像的居中部分。
您应该将源移动到图像的中间位置。工作代码:
public Bitmap getBitmapFromURL(String userId) {
try {
URL imgUrl = new URL("https://graph.facebook.com/" + userId + "/picture?type=large");
InputStream in = (InputStream) imgUrl.getContent();
Bitmap bitmap = BitmapFactory.decodeStream(in);
Bitmap output;
Rect srcRect;
if (bitmap.getWidth() > bitmap.getHeight()) {
output = Bitmap.createBitmap(bitmap.getHeight(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
srcRect = new Rect((bitmap.getWidth()-bitmap.getHeight())/2, 0, bitmap.getWidth()+(bitmap.getWidth()-bitmap.getHeight())/2, bitmap.getHeight());
} else {
output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getWidth(), Bitmap.Config.ARGB_8888);
srcRect = new Rect(0, (bitmap.getHeight()-bitmap.getWidth())/2, bitmap.getWidth(), bitmap.getHeight()+(bitmap.getHeight()-bitmap.getWidth())/2);
}
Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
float r = 0;
if (bitmap.getWidth() > bitmap.getHeight()) {
r = bitmap.getHeight() / 2;
} else {
r = bitmap.getWidth() / 2;
}
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, rect, paint);
return output;
} catch (IOException e) {
// Log exception
return null;
}
}