你到底在哪里添加那条线?如果它在你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);
并向转向线添加断点并对其进行调试。如果宽度和高度为 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();
}
}
您可以将其用于普通视图或表面视图,无论哪种方式都有效。对不起,如果答案有点太长:P