我有一个自定义视图组(包含加载毕加索的图像),可以在两个地方重复使用:
我绘制到画布的代码如下所示:
int measureSpec = View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY);
view.measure(measureSpec, measureSpec);
Bitmap bitmap =
Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
view.draw(canvas);
问题是在我将视图绘制到画布之前没有时间加载图像。我试图尽可能地避免在这里进行耦合,所以我不想添加毕加索的回调,因为进行绘图的班级并不了解它的观点。 #39;画。
我目前正在解决此问题,方法是将图片加载代码更改为.get()
而不是.load()
,然后再使用imageView.setImageBitmap()
。不幸的是,这给视图增加了很多复杂性,我真的不喜欢它。
我想做的是向Picasso的RequestCreator传递一个选项,即该请求应该在当前线程上同步执行(如果它是主线程则抛出异常)。我想知道这对于直接建立毕加索的支持来说是不是太过分了?或者它已经在API中了,我对它一无所知?
答案 0 :(得分:12)
这是我的解决方案:
/**
* Loads the request into an imageview.
* If called from a background thread, the request will be performed synchronously.
* @param requestCreator A request creator
* @param imageView The target imageview
* @param callback a Picasso callback
*/
public static void into(RequestCreator requestCreator, ImageView imageView, Callback callback) {
boolean mainThread = Looper.myLooper() == Looper.getMainLooper();
if (mainThread) {
requestCreator.into(imageView, callback);
} else {
try {
Bitmap bitmap = requestCreator.get();
imageView.setImageBitmap(bitmap);
if (callback != null) {
callback.onSuccess();
}
} catch (IOException e) {
if (callback != null) {
callback.onError();
}
}
}
}
答案 1 :(得分:2)
Jacob Tabak的完美答案
如果您将图片加载到Target
,这是一个小的附加处理案例。我还没有办法让图像的原点通过适当的LoadedFrom
参数。
public static void into(RequestCreator requestCreator, Drawable placeHolder, Drawable errorDrawable, Target target) {
boolean mainThread = Looper.myLooper() == Looper.getMainLooper();
if (mainThread) {
requestCreator.into(target);
} else {
try {
target.onBitmapFailed(placeHolder);
Bitmap bitmap = requestCreator.get();
target.onBitmapLoaded(bitmap, Picasso.LoadedFrom.MEMORY);
} catch (IOException e) {
target.onBitmapFailed(errorDrawable);
}
}
}