Tôi có đối tượng Bitmap trong lớp chính của mình. Tôi cần gửi bitmap này đến lớp xem tùy chỉnh của mình để đặt nó làm nền để xử lý tiếp trên canvas.Cách đặt hình ảnh bitmap trong canvas của Chế độ xem tùy chỉnh của tôi?
Ví dụ: có một phương pháp gọi là setPicture nhận bitmap làm tham số. Vì vậy, làm thế nào nó có thể vẽ bitmap này trên vải?
Xin xem đoạn code dưới đây:
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;
}
}
Làm thế nào tôi nên gửi bitmap này để OnDraw?
Doomsknight, cảm ơn rất nhiều! Nó hoạt động, bạn đã làm cho ngày của tôi! :)) – Carlos
Tôi nghĩ rằng câu hỏi là làm thế nào để có được biến myBitmap từ MainActivity đến chế độ xem tùy chỉnh. Trong câu trả lời của bạn, myBitmap sẽ không được xác định. – Donato
@ Donato Tôi đoán tôi đã thấy anh ấy gặp nhiều vấn đề hơn với việc vẽ hình ảnh hơn là chuyển nó sang chế độ xem tùy chỉnh. Đơn giản chỉ cần tạo một phương thức để đặt bitmap/id tham chiếu hoặc thêm nó làm tham số trong hàm tạo. – Doomsknight