2011-11-10 55 views
0

我想我對如何使用自定義視圖有點困惑。我正在跟隨來自Square的Eric Burke的演講幻燈片(來自今年的anddevcon,幻燈片在這裏:http://www.andevcon.com/AndevCon_II/downloadpresentation.aspx?aid=Taming_Android__User_Experience_Lessons_from_Square_pdf.zip&sid=2)。如何使用自定義視圖,例如設置可繪製

他的代碼,或者至少他表現出的幻燈片,一部分去了這樣的事情:

public class EditablePhoto extends View { 

    private Bitmap framedPhoto; 
    private Bitmap image; 
    private Drawable placeholder; 

    public EditablePhoto(Context context) { 
     super(context); 
    } 

    @Override protected void onMeasure(int widthMeasureSpec, 
             int heightMeasureSpec) { 
     int measuredWidth = getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec); 
     int measuredHeight = getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec); 

     //ensure view always square 
     int min = Math.min(measuredHeight, measuredWidth); 
     setMeasuredDimension(min, min); 

    } 

    @Override 
    protected void onDraw(Canvas canvas) { 
     if(placeholder == null && image==null) return; 

     if(framedPhoto == null) { 
      createFramedPhoto(Math.min(getWidth(), getHeight())); 
     } 

     canvas.drawBitmap(framedPhoto, 0, 0, null); 
    } 

    private void createFramedPhoto(int size) { 

     Drawable imageDrawable = (image!=null) 
       ? new BitmapDrawable(image) : placeholder; 

     Bitmap output = Bitmap.createBitmap(size, size, 
       Bitmap.Config.ARGB_8888); 

     Canvas canvas = new Canvas(output); 

     RectF outerRect = new RectF(0, 0, size, size); 
     float outerRadius = size/18f; 

     //Red rectangle 

     Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); 
     paint.setColor(Color.RED); 

     canvas.drawRoundRect(outerRect, outerRadius, outerRadius, paint); 

     paint.setXfermode(new PorterDuffXfermode(
       PorterDuff.Mode.SRC_IN)); 

     imageDrawable.setBounds(0, 0, size, size); 
     canvas.saveLayer(outerRect, paint, Canvas.ALL_SAVE_FLAG); 
     imageDrawable.draw(canvas); 
     canvas.restore(); 
    } 
} 

我不明白的是如何實際使用該視圖現在....在哪裏,你什麼時候設置位圖,這是該類中的私有字段......?

一般困惑和會愛一些啓示。

回答

-1

OnDraw()是您將在畫布上繪製視圖的方法。在這裏你也可以分析onDraw()會調用CreateFramePhoto然後在畫布上繪製這個Bitmap。

可以在佈局無論是從XML或Java中

1)通過XML添加此customView:

<EditablePhoto android:layout_height="wrap_content" 
     android:layout_gravity="center_vertical" 
       .......................... 
/> 

不forgate添加構造EditablePhoto(上下文的背景下,AttributeSet中的屬性集中)爲這種情況下

2)通過Java類:

EditablePhoto editablePhoto = new EditablePhoto(this); 
addView(editablePhoto) // or do anthing you want with this 
+0

感謝您的嘗試,但這只是真的不回答這個問題。你所做的只是解釋一般的onDraw的功能。你沒有回答如何實際設置位圖/繪圖。 – LuxuryMode

+0

通過構造函數傳遞位圖。 EditablePhoto(上下文上下文,AttributeSet屬性集,位圖位圖)並將其保存在類中並使用它 –

+0

您的查詢「我沒有得到的是如何實際使用此視圖....」以錯誤的方式指示我。將欣賞你downVote,如果你會正確描述你的問題 –

0

超過一年過去了,但我希望這會幫助任何尋找正確答案的人。在我的情況下,我推出了這行代碼

framedPhoto = output; 

作爲createFramedPhoto()方法中的最後一個。有用。 在該示例中,作者創建了一個圓角矩形作爲背景,然後使用XOR模式在其上繪製位圖,因此圓角矩形外的所有像素都將被裁掉。

相關問題