Han*_*ney 7 java android background-image surfaceview drawable
有没有办法设置SurfaceView的背景图像?是否必须在xml中完成,或者我可以用Java完成所有操作 - 我的构造函数中有一些看起来像这样的东西:
Drawable sky = (getResources().getDrawable(R.drawable.sky));
this.setBackgroundDrawable(sky);
Run Code Online (Sandbox Code Playgroud)
但它仍然没有显示任何东西.
虽然您无法直接将背景图像设置为a SurfaceView,但您可以重叠ImageView(显示背景图像)和您的背景图像SurfaceView,使其透明.
绘制一个1920x1080位图作为每个SurfaceView重绘的背景图像时,我遇到了性能问题:我找到的唯一解决方案(感谢这个答案)是使用ImageView显示这个1920x1080(固定)位图,并使用我SurfaceView的顶部,制作它透明,避免为每次SurfaceView重绘绘制大背景图像.现在我的应用程序更顺畅,多亏了这段代码:
// Setup your SurfaceView
SurfaceView surfaceView = ...; // use any SurfaceView you want
surfaceView.setZOrderOnTop(true);
surfaceView.getHolder().setFormat(PixelFormat.TRANSPARENT);
// Setup your ImageView
ImageView bgImagePanel = new ImageView(context);
bgImagePanel.setBackgroundResource(...); // use any Bitmap or BitmapDrawable you want
// Use a RelativeLayout to overlap both SurfaceView and ImageView
RelativeLayout.LayoutParams fillParentLayout = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.FILL_PARENT);
RelativeLayout rootPanel = new RelativeLayout(context);
rootPanel.setLayoutParams(fillParentLayout);
rootPanel.addView(surfaceView, fillParentLayout);
rootPanel.addView(bgImagePanel, fillParentLayout);
Run Code Online (Sandbox Code Playgroud)
然后你应该SurfaceView用这个开始你的绘画方法:(为了"刷新" SurfaceView缓冲区中先前绘制的图像)
canvas.drawColor(0, PorterDuff.Mode.CLEAR);
Run Code Online (Sandbox Code Playgroud)
试试这个
public void surfaceCreated(SurfaceHolder arg0) {
Bitmap background = BitmapFactory.decodeResource(getResources(), R.drawable.background);
float scale = (float)background.getHeight()/(float)getHeight();
int newWidth = Math.round(background.getWidth()/scale);
int newHeight = Math.round(background.getHeight()/scale);
Bitmap scaled = Bitmap.createScaledBitmap(background, newWidth, newHeight, true);
}
public void onDraw(Canvas canvas) {
canvas.drawBitmap(scaled, 0, 0, null); // draw the background
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15134 次 |
| 最近记录: |