Ответ 1
Да, вы можете это сделать. Имейте в виду, так как вы не привязываете его к макету, вам нужно его вручную выложить, прежде чем рисовать:
view.layout(0, 0, viewWidth, viewHeight);
И если вы точно не знаете, что именно вы хотите для этих параметров ширины и высоты, вы также можете сначала его измерить:
int widthSpec = MeasureSpec.makeMeasureSpec (ViewGroup.LayoutParams.WRAP_CONTENT, MeasureSpec.UNSPECIFIED;
int heightSpec = MeasureSpec.makeMeasureSpec (400, MeasureSpec.UNSPECIFIED;
view.measure(widthSpec, heightSpec);
view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
EDIT:
Если вы уже знаете ширину и высоту, вам нужно:
//Lay the view out with the known dimensions
view.layout (0, 0, rect.width(), rect.height());
//Translate the canvas so the view is drawn at the proper coordinates
canvas.save();
canvas.translate(rect.left, rect.top);
//Draw the View and clear the translation
view.draw(canvas);
canvas.restore();
ИЗМЕНИТЬ еще раз:
Да, проверено. Вы можете попробовать это самостоятельно:
public class DrawingActivity extends Activity {
public void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Set a Rect for the 200 x 200 px center of a 400 x 400 px area
Rect rect = new Rect();
rect.set(100, 100, 300, 300);
//Allocate a new Bitmap at 400 x 400 px
Bitmap bitmap = Bitmap.createBitmap(400, 400, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
//Make a new view and lay it out at the desired Rect dimensions
TextView view = new TextView(this);
view.setText("This is a custom drawn textview");
view.setBackgroundColor(Color.RED);
view.setGravity(Gravity.CENTER);
//Measure the view at the exact dimensions (otherwise the text won't center correctly)
int widthSpec = View.MeasureSpec.makeMeasureSpec(rect.width(), View.MeasureSpec.EXACTLY);
int heightSpec = View.MeasureSpec.makeMeasureSpec(rect.height(), View.MeasureSpec.EXACTLY);
view.measure(widthSpec, heightSpec);
//Lay the view out at the rect width and height
view.layout(0, 0, rect.width(), rect.height());
//Translate the Canvas into position and draw it
canvas.save();
canvas.translate(rect.left, rect.top);
view.draw(canvas);
canvas.restore();
//To make sure it works, set the bitmap to an ImageView
ImageView imageView = new ImageView(this);
imageView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
setContentView(imageView);
imageView.setScaleType(ImageView.ScaleType.CENTER);
imageView.setImageBitmap(bitmap);
}
}