2013-01-05 54 views
6

我在我的主類有一個位圖對象。我需要將此位圖發送到我的自定義視圖類,以將其設置爲畫布上進一步處理的背景。如何在我的自定義視圖的畫布中設置位圖圖像?

例如,有一種稱爲setPicture的方法,它接收位圖作爲參數。那麼,如何在畫布上繪製這個位圖呢?

請參閱下面的代碼:

public class TouchView extends View { 

final int MIN_WIDTH = 75; 
final int MIN_HEIGHT = 75; 
final int DEFAULT_COLOR = Color.RED; 
int _color; 
final int STROKE_WIDTH = 2; 

private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); 
private float x, y; 
private boolean touching = false; 

public TouchView(Context context, AttributeSet attrs, int defStyle) { 
    super(context, attrs, defStyle); 
    // TODO Auto-generated constructor stub 
    init(); 
} 

public TouchView(Context context, AttributeSet attrs) { 
    super(context, attrs); 
    // TODO Auto-generated constructor stub 
    init(); 
} 

public TouchView(Context context) { 
    super(context); 
    // TODO Auto-generated constructor stub 
    init(); 
} 

private void init() { 
    setMinimumWidth(MIN_WIDTH); 
    setMinimumHeight(MIN_HEIGHT); 
    _color = DEFAULT_COLOR; 
} 

@Override 
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 
    // TODO Auto-generated method stub 
    setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), 
      MeasureSpec.getSize(heightMeasureSpec)); 
} 

@Override 
protected void onDraw(Canvas canvas) { 
    // TODO Auto-generated method stub 
    super.onDraw(canvas); 

    if (touching) { 
     paint.setStrokeWidth(STROKE_WIDTH); 
     paint.setColor(_color); 
     paint.setStyle(Paint.Style.FILL); 
     canvas.drawCircle(x, y, 75f, paint); 
    } 
} 

public void setPicture (Bitmap bitmap) { 

     /////// 
     This method must receive my bitmap to draw it on canvas!!!!!!!!!!!!!!! 
     /////// 


} 

public void setColor(int color) { 
    _color = color; 
} 

@Override 
public boolean onTouchEvent(MotionEvent motionEvent) { 
    // TODO Auto-generated method stub 

    switch (motionEvent.getAction()) { 
    case MotionEvent.ACTION_MOVE: 
    case MotionEvent.ACTION_DOWN: 
     x = motionEvent.getX(); 
     y = motionEvent.getY(); 
     touching = true; 
     break; 
    default: 
     touching = false; 
    } 
    invalidate(); 
    return true; 
} 

}

我應該如何發送此位圖的OnDraw?

回答

6

裏面你onDraw()方法,

只是做

canvas.drawBitmap(myBitmap, 0, 0, null); 

MYBITMAP是您的位圖的變量。

0,0指的是繪製在左上角的座標。

還有其他可用的API,來繪製到某些區域等

More info can be found here in the api docs.

或者: 代替延伸ImageView的,並使用setImageBitmap(Bitmap src);方法實現這一目標。

+2

Doomsknight,非常感謝!它的作品,你讓我的一天! :)) – Carlos

+0

我認爲這個問題是如何將myBitmap變量從MainActivity獲取到自定義視圖。在你的答案中,myBitmap將是未定義的。 – Donato

+0

@Donato我想我看到他在繪製圖像時比將圖像傳遞給自定義視圖更麻煩。只需創建一個設置參考位圖/ ID的方法,或者將其作爲參數添加到構造函數中。 – Doomsknight

0

將位圖轉換爲drawable並使用View類的setBackgroundDrawable方法。

public void setPicture (Bitmap bitmap) { 
    setBackgroundDrawable(new BitmapDrawable(bitmap)); 
} 
+0

Leonidos,謝謝你也可以,但我注意到這種方法延伸圖片以適應組件。是否可以看到我的照片在實際尺寸或正確的比例? – Carlos

+0

是的,例如,將BitmapDrawable的引力設置爲「頂部」。閱讀有關BitmapDrawable的文檔。它有很多功能。 – Leonidos

相關問題