その行を正確にどこに追加しますか?その場合onCreate
、メソッド以降の画像は表示されず、getWidth()
0getHeight()
が返されます。したがって、ペイントするには、システムが実際にビューを作成するまで待つ必要があります。実際に値を受け取っていることをテストするには、実際に持っているコードを次のように変更してみてください。
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);
ステアリングラインにブレークポイントを追加してデバッグします。幅と高さが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