首页 > 解决方案 > 可以设置 ImageView 以便仅在某些情况下调用 onDraw 吗?

问题描述

我的应用需要显示一组图像。一些图像是内置的,而其他图像是由用户添加的。我为此创建了一个类,称为SymbolBox(我在这里简化了它):

public class SymbolBox extends android.support.v7.widget.AppCompatImageView {

 private FullSymbol  mSymbol; // Symbol to show                 
 private final Paint mPaint;  // Paint variable to use

 // Constructor initialises options and sets up the paint object
 public SymbolBox(Context context, AttributeSet attrs) {
        super(context, attrs);

        mPaint          = new Paint();

 }

 // Set the symbol
 public void setSymbol(FullSymbol symbol) { 
    this.mSymbol = symbol; 
 }

 // Draw the symbol
 protected void onDraw(Canvas canvas) {

   if(this.mSymbol == null) return;
   String drawableUrl  = mSymbol.getUrl();
   if(drawableUrl != null) return;  // Only use this to draw from base

   // Get canvas size
   float height = getHeight();
   float width  = getWidth();

   // Draw the symbol
   String drawableName = mSymbol.getBase();
   Context context = getContext();


     if((drawableName == null) || (drawableName.equals(""))) { drawableName = "blank"; }

     Resources resources = context.getResources();
     final int resourceId = resources.getIdentifier(drawableName,
                    "drawable",
                    context.getPackageName());

     Drawable d;
     if (resourceId != 0) {
       if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
         d = resources.getDrawable(resourceId, context.getTheme());
       } else {
         d = resources.getDrawable(resourceId);
       }
       d.setBounds(0, 0, getWidth(), getHeight());
       d.draw(canvas);
     }
}

FullSymbol定义如下:

public class FullSymbol {

    private String  name, base;
    private String  url;

    // CONSTRUCTOR
    public FullSymbol() {}

    public String getBase() { return this.base; }
    public String getName() { return name; }
    public String getUrl() { return url; }

    public void setBase(String newBase) { this.base = newBase; }
    public void setName(String newName) { this.name = newName; }
    public void setUrl(String newUrl)   { this.url = newUrl; }
}

每个都FullSymbol可以有 abase或 a url(如果两者都没有,则基数将设置为“空白”)。base是对内置图像的引用;url是对在线图像(已由用户上传)的引用。

在调用所有这些的片段中,我SymbolBox在布局中设置一个,然后使用Glide将图像加载到SymbolBox(我在下载上传的图像时遇到问题,所以现在只使用固定的 url):

SymbolBox test = rootView.findViewById(R.id.testSymbol);
Glide.with(this).load("http://path/to/image").into(test);

因此,如果 FullSymbol 有一个 url,那么该 url 处的图像应该使用 Glide 加载到 SymbolBox 中。如果它没有 url,那么应该使用 base 的值,并使用 drawables 绘制图像。

我遇到的问题是 Glide 部分仅在从 SymbolBox 类中取出 onDraw 时才显示任何内容(即完全注释掉;如果我只有一个空函数它不起作用)。但是如果没有 url 并且我正在使用基础,我需要 onDraw 来绘制图像。

如果 url 存在,有没有办法以某种方式忽略 onDraw,否则包含它?或者从基础绘制的另一种方式 - 我可以创建一个函数,但我需要访问 Canvas。我该如何解决这个问题?

标签: imageviewandroid-drawableandroid-glideondraw

解决方案


我设法解决了这个问题 - 我添加了对insuper方法的调用:onDrawSymbolBox

protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

   ... rest of the code stayed the same ...

}

它奏效了。


推荐阅读