到目前为止,我的图像从0,0开始并正确缩放。它下面有一个黑色的酒吧。如何对齐它以使其沿y居中,图像上方和下方有黑条?
编辑:同样,什么是“this.getWidth(),this.getHeight()”指的是当我将对象设为“dest”时 - mBitmap的宽度?文档确实说它们代表了视图的宽度,我只是想确保我认为它是正确的mBitmap。
public class SpotGameActivity extends Activity {
private Bitmap mBitmap;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.dpi2b);
setContentView(new BitMapView(this, mBitmap));
}
class BitMapView extends View {
Bitmap mBitmap = null;
public BitMapView(Context context, Bitmap bm) {
super(context);
mBitmap = bm;
}
@Override
protected void onDraw(Canvas canvas) {
//DisplayMetrics metrics = new DisplayMetrics();
//getWindowManager().getDefaultDisplay().getMetrics(metrics);
// called when view is drawn
Paint paint = new Paint();
paint.setFilterBitmap(true);
// The image will be scaled so it will fill the width, and the
// height will preserve the image’s aspect ration
float aspectRatio = ((float) mBitmap.getWidth()) / mBitmap.getHeight();
Rect dest = new Rect(0, 0, this.getWidth(),(int) (this.getWidth() / aspectRatio));
String AR = Double.toString(aspectRatio);
canvas.drawBitmap(mBitmap, null, dest, paint);
Toast.makeText(SpotGameActivity.this, AR, Toast.LENGTH_SHORT).show();
}
我现在已经看到了视图大小和图像大小之间的差异。我把差异除以2但是现在,我的图像对齐到屏幕的底部而不是y轴的中间。任何提示?:
@Override
protected void onDraw(Canvas canvas) {
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int scrHeight = this.getHeight();
String sH = Integer.toString(scrHeight);
Log.v(TAG, "scrHeight =" + sH );
int imgHeight= mBitmap.getHeight();
String iH = Integer.toString(imgHeight);
Log.v(TAG, "imgHeight =" + iH );
int diff = scrHeight - imgHeight;
String dif = Integer.toString(diff);
Log.v(TAG, "diff =" + dif );
int dvd= diff/2;
// called when view is drawn
Paint paint = new Paint();
paint.setFilterBitmap(true);
// The image will be scaled so it will fill the width, and the
// height will preserve the image’s aspect ration
float aspectRatio = ((float) mBitmap.getWidth()) / mBitmap.getHeight();
Rect dest = new Rect(0, dvd, this.getWidth(),(int) (this.getWidth() / aspectRatio)+dvd);
String AR = Double.toString(dvd);
canvas.drawBitmap(mBitmap, null, dest, paint);
Toast.makeText(SpotGameActivity.this, AR, Toast.LENGTH_SHORT).show();