你究竟在哪裏添加該行?如果它在你的onCreate
那麼它不會顯示你的圖像,因爲方法getWidth()
和getHeight()
將返回0.所以要繪製它,你必須等到系統實際創建了視圖。 要測試你實際接收值嘗試改變你確實有代碼這樣的事情:
final int width = getWidth();
final int height = getHeight();
final Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
steering = new Steering(bitmap, width-50,height-50);
和斷點添加到轉向線和debugg它。如果你的寬度和高度爲0,那麼你將不得不等待視圖畫出。
編輯: 您Activity
/Fragment
你可以添加一個樹的觀察者是這樣的:
myView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
//Do something here since now you have the width and height of your view
}
});
這裏是你會怎麼做它在你的類一個小例子:
我的轉向系類別:
public class Steering {
private Bitmap mBitmap;
private int mWidth;
private int mHeight;
public Steering(Bitmap bitmap, int width, int height) {
this.mBitmap = bitmap;
this.mWidth = width;
this.mHeight = height;
}
public Bitmap getBitmap() {
//reescaling from anddev.org/resize_and_rotate_image_-_example-t621
final int imageWidth = mBitmap.getWidth();
final int imageHeight = mBitmap.getHeight();
// calculate the scale -
float scaleWidth = ((float) mWidth)/imageWidth;
float scaleHeight = ((float) mHeight)/imageHeight;
// createa matrix for the manipulation
Matrix matrix = new Matrix();
// resize the bit map
matrix.postScale(scaleWidth, scaleHeight);
Bitmap resizedBitmap = Bitmap.createBitmap(mBitmap, 0, 0, imageWidth, imageHeight, matrix, true);
return resizedBitmap;
}
}
我的動態
public class MainActivity extends Activity {
MyView mView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mView = (MyView) findViewById(R.id.viewid);
OnGlobalLayoutListener listener = new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
final int width = mView.getWidth();
final int height = mView.getHeight();
final Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.android);
//image from anddev
final Steering steering = new Steering(bitmap, width-50,height-50);
mView.setObject(steering);
}
};
mView.getViewTreeObserver().addOnGlobalLayoutListener(listener);
}
}
和我的視圖類
public class MyView extends View{
Steering steering = null;
public MyView(Context context) {
super(context);
}
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setObject(Steering steering){
this.steering = steering;
}
final Paint paint = new Paint();
@Override
protected void onDraw(Canvas canvas) {
canvas.save();
if(steering!=null){
canvas.drawBitmap(steering.getBitmap(), 0, 0, paint);
}
canvas.restore();
}
}
您可以使用此爲普通視圖或surfaceView,兩種方法都可行。 對不起,如果答案有點太長:P
所以沒有辦法att在構造函數中使用這些方法嗎? –
不,但在您的活動中,您可以使用treeobserver ..我剛剛更新了我的答案:) – Raykud
感謝您的幫助,但無法讓那個人工作,即時通訊新的android編程如此。但是,無論如何感謝:) –