2013-08-30 71 views
1

我嘗試實現自己的drawable,將cors從一個簡單的彩色矩形(應該與drawable所在的ImageView的大小相同)淡出到加載的位圖(通過http) 。可繪製:瞭解畫布寬度和高度

所以我做的是重寫的draw()方法我的繪製對象:

public void draw(Canvas canvas) { 
     boolean done = true; 

     Log.d("Test", 
       "canvas w: " + canvas.getWidth() + " " + canvas.getHeight()); 


     final int alpha = mAlpha; 
     final boolean crossFade = mCrossFade; 

     Paint paint = mStartPaint; 
     paint.setColor(blueColor); 

     if (!crossFade || 255 - alpha > 0) { 
      if (crossFade) { 
       paint.setAlpha(255 - alpha); 
      } 

      // Draw the rect with the color 
      canvas.drawRect(0, 0, canvas.getWidth(), canvas.getHeight(), paint); 

      if (crossFade) { 
       paint.setAlpha(0xFF); 
      } 

     } 

     if (alpha > 0) { 
      Bitmap bitmap = mEnd; 
      paint = mEndPaint; 
      paint.setAlpha(alpha); 
      if (mBitmapScalingType == null) 
       canvas.drawBitmap(bitmap, mEndX, mEndY, paint); 
      else 
       mBitmapScalingType.draw(bitmap, canvas.getWidth(), 
         canvas.getHeight(), canvas, paint); 

      paint.setAlpha(0xFF); 
     } 

     if (!done) { 
      mHandler.post(mInvalidater); 
     } 
    } 

所以canvas.getWidth()和canvas.getHeight()返回128(寬度)和150(高度),其和ImageView一樣。但結果是:

enter image description here

藍色矩形沒有被塗在整個畫布,我不能找出原因。

顯示我的fadeable drawable的ImageView沒有特定的scaletype集。

任何想法可能是錯的?

我也注意到,寬度和高度從的setBounds()計算出的是180×212像素

@Override 
public void setBounds(int left, int top, int right, int bottom) { 
    super.setBounds(left, top, right, bottom); 

    final int width = right - left; 
    final int height = bottom - top; 
      Log.d("Test", "width: "+width+" height: "+height); 
    } 

,如果我繪製顏色與180×212像素

canvas.drawRect(0, 0, 180, 212, paint); 

矩形現在被繪製完全填充畫布。

任何想法可能是錯誤的?

Btw。該ImageView的定義那樣:

<ImageView android:id="@+id/playerPic" 
      android:layout_width="64dp" 
      android:layout_height="75dp"   
      android:layout_marginRight="10dp" 
      /> 
在xhdpi

64dp = 128像素和75dp = 150像素

回答

1

這個答案並不能解釋尺寸的差異,但有時它更容易只是做的事情不同的方式。

如果您只是想用顏色填充畫布,則不需要使用drawRect(),只需使用drawColor()即可。有一個簡單的版本,只需要一個Color,一個可以讓你指定一個porter-duff模式。這樣你根本不需要尺寸,你可以避免整個事情。

-1

也許你可以嘗試使用DisplayMetrics來獲得尺寸。

//Get the width and height of the screen 
    DisplayMetrics d = new DisplayMetrics(); 
    getWindowManager().getDefaultDisplay().getMetrics(d); 
    int width = d.widthPixels; 
    int height = d.heightPixels; 

然後只需調用drawRect中使用這些值

canvas.drawRect(0, 0, width, height, paint);