SurfaceView 中的'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 中,资源是用于访问应用程序资源的类。您可以从以下位置获取此类的实例

  • 上下文类或其子类的实例,如应用程序、活动、服务等。
  • View 类或其子类(如 TextView、Button、SurfaceView 等(的实例。

在这种情况下,您可以在创建节点实例时传递 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)
}
}

然后在节点类中使用它

// 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)
...
}

它是 Android 资源对象。 您可以通过 Context.resources 从任何Context子类访问它,例如您的Activity。 请注意,您需要ContextActivity的特定实例 - 仅编写Activity.resources是行不通的。

最新更新