我希望我的位图在我的屏幕中心..我试着这样但它不工作…
Bitmap myBitmap = BitmapFactory.decodeResource(getResources(),R.drawable.compass); int w = canvas.getWidth(); int h = canvas.getHeight(); int bw=myBitmap.getWidth(); int bh=myBitmap.getHeight(); int cx = w / 2; int cy = h / 2; display d = getwindowManager().getDefaultdisplay(); int x = d.getWidth(); int y = d.getHeight(); int dx = x / 2; int dw = y /2; canvas.translate(cx,cy); if (mValues != null) { canvas.rotate(-mValues[0]); } int centreX = (x - bw) /2; int centreY = (cy - bh) /2; //canvas.drawPath(mPath,mPaint); canvas.drawBitmap(myBitmap,centreX,centreY,null);
解决方法
以下是您在视图中需要的代码:
private int mWidth; private int mHeight; private float mAngle; @Override protected void onMeasure(int widthMeasureSpec,int heightMeasureSpec) { mWidth = View.MeasureSpec.getSize(widthMeasureSpec); mHeight = View.MeasureSpec.getSize(heightMeasureSpec); setMeasuredDimension(mWidth,mHeight); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); Bitmap myBitmap = BitmapFactory.decodeResource(getResources(),R.drawable.compass); // Here's the magic. Whatever way you do it,the logic is: // space available - bitmap size and divide the result by two. // There must be an equal amount of pixels on both sides of the image. // Therefore whatever space is left after displaying the image,half goes to // left/up and half to right/down. The available space you get by subtracting the // image's width/height from the screen dimensions. Good luck. int cx = (mWidth - myBitmap.getWidth()) >> 1; // same as (...) / 2 int cy = (mHeight - myBitmap.getHeight()) >> 1; if (mAngle > 0) { canvas.rotate(mAngle,mWidth >> 1,mHeight >> 1); } canvas.drawBitmap(myBitmap,cx,cy,null); }
截图只是为了好玩:http://imgur.com/EYpMJ
(对角线不是此处发布的代码的一部分)
编辑:添加了NickT的解决方案.编辑2:将mvalues [0]更改为mAngle并使其成为条件.将2次操作除以更改为位移.如果您不需要,请删除旋转代码.
原文地址:https://www.jb51.cc/android/312013.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。