我正在尝试使用Sprite编写应用程序。现在,我正在将图像传递给每个精灵对象。但是由于每个精灵的图像都是相同的,所以我宁愿将图像存储为类属性。不幸的是,变量“ resources”只能在SurfaceView类中访问,而不能在sprite类中访问。这是我的代码的相关部分:
import android.content.Context
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Paint
import android.util.AttributeSet
import android.util.Log.d
import android.view.SurfaceHolder
import android.view.SurfaceView
import android.view.View
import java.lang.Exception
import java.util.*
import kotlin.collections.ArrayList
class GameView(context: Context, attributes: AttributeSet): SurfaceView(context, attributes), SurfaceHolder.Callback {
override fun surfaceCreated(p0: SurfaceHolder?) {
Note(BitmapFactory.decodeResource(resources, R.drawable.note), 200)
}
}
注释代码:
import android.content.res.Resources
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.util.Log.d
class Note (var image: Bitmap, var x: Int) {
var y: Int = 0
var width: Int = 0
var height: Int = 0
private var vx = -10
private val screenWidth = Resources.getSystem().displayMetrics.widthPixels
private val screenHeight = Resources.getSystem().displayMetrics.heightPixels - 100
// I would like to load the image like this:
private val image2: Bitmap = BitmapFactory.decodeResource(resources, R.drawable.note)
init {
width = image.width
height = image.height
//x = screenWidth/2
y = ((screenHeight-height)/2).toInt()
}
fun draw(canvas: Canvas) {
canvas.drawBitmap(image, x.toFloat(), y.toFloat(), null)
}
fun update(){
x += vx
if (x < 0) {
x = screenWidth
}
}
}
我尝试使用GameView.resources和SurfaceView.resources,但均无效。资源变量来自哪里,如何访问?
这是Android Resources对象。您可以从任何Context.resources子类中通过Context
访问它,例如Activity
。请注意,您需要Context
或Activity
的特定实例-仅写Activity.resources
无效。
在Android中,Resources是用于访问应用程序资源的类。您可以从
获取此类的实例在您的情况下,您可以在创建Node实例时传递GameView类(View类的子类)的上下文实例。
class GameView(context: Context, attributes: AttributeSet): SurfaceView(context, attributes), SurfaceHolder.Callback { override fun surfaceCreated(p0: SurfaceHolder?) { // Pass context that associated with this view to Node constructor. Note(context, BitmapFactory.decodeResource(resources, R.drawable.note), 200) } }
然后在Node类中使用它
// Modify Node constructor to add a Context parameter. class Note (val context: Context, var image: Bitmap, var x: Int) { ... // Get resources instance from a Context instance. private val image2: Bitmap = BitmapFactory.decodeResource(context.resources, R.drawable.note) ... }