2013-10-23 19 views
7

我最近從ImageView中創建了一個CircularImageView類,該類使圖像以彩色邊框呈圓形。這是通過繪製到該傳入的帆布通過的onDraw(Canvas)的方法來完成:自定義ImageView類不能與Picasso圖像下載庫一起工作

//load the bitmap 
    loadBitmap(); 

    // init shader 
    if(image !=null) 
    { 
     shader = new BitmapShader(Bitmap.createScaledBitmap(image, viewWidth + (borderWidth * 2), viewHeight + (borderWidth * 2), true), Shader.TileMode.CLAMP, Shader.TileMode.CLAMP); 
     paint.setShader(shader); 

     int circleCenter = viewWidth/2; 

     // circleCenter is the x or y of the view's center 
     // radius is the radius in pixels of the cirle to be drawn 
     // paint contains the shader that will texture the shape 
     canvas.drawCircle(circleCenter + borderWidth, circleCenter + borderWidth, circleCenter + borderWidth, paintBorder); 
     canvas.drawCircle(circleCenter + borderWidth, circleCenter + borderWidth, circleCenter, paintBackground); 
     canvas.drawCircle(circleCenter + borderWidth, circleCenter + borderWidth, circleCenter, paint); 
    } 

所以這一點通過繪製或位圖設置圖像時有效。我也擴展了它,所以我可以將它與谷歌的Volley NetworkImageView一起使用。

我的問題來了,當我嘗試和我們的CircularImageView類一起Picasso圖像下載庫,因爲我正在看它作爲Volley的替代品。在獲取BitmapDrawable時,第一行的loadBitmap()函數中出現ClassCastException。

private void loadBitmap() 
{ 
    BitmapDrawable bitmapDrawable = (BitmapDrawable) this.getDrawable(); 

    if(bitmapDrawable != null) 
     image = bitmapDrawable.getBitmap(); 
} 

Initally畢加索已下載的圖片前幾輪的圖像佔位符就好了。但是一旦圖像被Picasso下載,就會失敗,並返回一個ClassCastException,並返回PicassoDrawable而不是BitmapDrawable。

我想繼續工作,在我的CircularImageView類中的onDraw(canvas)方法中對圖像進行四捨五入,因爲它很好地包含並自動執行,而不是每次使用Picasso設置ImageView時進行的過程。這可能嗎?

在此先感謝。

回答

14

對於使用Picasso的圓形圖像,請使用this實現Transformation的類。

Picasso.with(context).load(url).transform(new RoundedTransformation(radius, margin)).into(imageview); 
+0

這會每次創建一個新的位圖,不是? – secureboot

+0

感謝DesertIvy,droidx和傑克沃頓的幫助。這個項目被擱置,現在只是回到問題。我剛剛嘗試了上面的作品,完美。 –

5

當畢加索這樣做,你應該:

  1. 應用四捨五入爲Transformation,使圓角位圖緩存在內存中,或
  2. 鉗在自定義ImageView子着色器畫布。這種技術的詳細信息是由拉金cagin'概述羅曼蓋伊on his blog

試圖拉底層BitmapImageView的是一個反模式。如果您確實需要訪問Bitmap(並且您不需要,則應使用上述其中一種方法),在您的視圖中執行Target,其回調將提供onBitmapSuccess

相關問題