从 URL 下载图像并在 canvas - Android 上绘制

Download image from URL and draw it on canvas - Android

我正在尝试使用 Retrofit 库从服务器下载图像。服务器 returns 图像的字节数组,然后使用 BitmapFactory.decodeByteArray(..) 将其转换为位图。但是当我调用 canvas.drawBitmap(..) 时,我的应用程序崩溃并且以下消息显示在 LogCat

Fatal signal 11 (SIGSEGV), code 1, fault addr 0x188 android

在 Whosebug 上搜索后,我发现一个答案说将 android:hardwareAccelerated 设置为 false。我做到了,不仅我的应用程序变得迟钝和缓慢,图像仍然没有在 canvas 上绘制。我知道在 canvas.drawBitmap(....) 中传递的 lefttop 坐标是正确的,因为我可以显示从 mipmap 加载的图像。

任何对此的帮助将不胜感激,因为我在这个问题上停留了一段时间并且找不到合适的解决方案。

编辑

LogCat 崩溃时

                         ----Beginning of crash
A/libc: Fatal signal 11 (SIGSEGV), code 1, fault addr 0x188 in tid 22133
W/System: ClassLoader referenced unknown path: /data/app/com.i2c.bb4me-2/lib/x86_64
I/MultiDex: VM with version 2.1.0 has multidex support
I/MultiDex: install
I/MultiDex: VM has multidex support, MultiDex support library is disabled.
I/GMPM: App measurement is starting up, version: 8487
I/GMPM: To enable debug logging run: adb shell setprop log.tag.GMPM VERBOSE
I/AppCompatViewInflater: app:theme is now deprecated. Please move to using android:theme instead.
W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable

获取和绘制图像调用的方法

我在 onDraw() 中调用这个方法是在像我上面说的那样计算出正确的 left 和 top 之后。

private void getBitmap(final Canvas canvas, long imageID, final float left, final float top, final Paint paint) {
        ProfileService profileServiceRetrieveImage = AppManager.getServiceManager().getService(ProfileService.class);
        Call<ServerResponse<FetchProfileImageResponse>> call = profileServiceRetrieveImage.fetchProfileImage("retrieveImage.action", "", imageID);
        call.enqueue(new RetrofitCallback<ServerResponse<FetchProfileImageResponse>>() {
            @Override
            protected void onSuccess(ServerResponse<FetchProfileImageResponse> objectServerResponse) {
                FetchProfileImageResponse dao = objectServerResponse.getResponsePayload();
                Bitmap bmp = BitmapFactory.decodeByteArray(dao.getBinaryData(), 0, dao.getBinaryData().length);
                canvas.drawBitmap(bmp, left, top, paint);
            }
        });
    }

发布解决方案以防有人像我一样被困在这个问题上。

首先,不要在onSuccess中调用canvas.drawBitmap(....)。只需将从 onSuccess 检索到的位图保存在 class 中,调用 invalidate() 并在 onDraw()

中调用 canvas.drawBitmap(...)