我正在构建一个自定义视图,用于扩展视图和获取图像的参数。到目前为止,我已经实现了从一个绘图和服务器(通过字符串URL)绘制图像。
class CustomView(context: Context, attrSet: AttributeSet) : View(context){
private var typedArray = context.obtainStyledAttributes(attrSet, R.styleable.CustomView)
private var viewColor = typedArray.getColor(R.styleable.CustomView_viewColor, Color.WHITE)
private var viewSize = typedArray.getDimensionPixelSize(R.styleable.CustomView_viewSize, 200)
private var rect = Rect(50, 50, this.left+viewSize, this.top+viewSize)
var viewImage = typedArray.getResourceId(R.styleable.CustomView_viewImage, -1)
var imageBitmap:Bitmap?=null
var imageString = typedArray.getString(R.styleable.CustomView_imageString)
val radius = 100f
var cx = 0f
var cy = 0f
private var paint = Paint(Paint.ANTI_ALIAS_FLAG)
private var circlePaint = Paint(Paint.ANTI_ALIAS_FLAG)
private var labelPaint = Paint(Paint.ANTI_ALIAS_FLAG)
init {
paint.color = viewColor
circlePaint.color = Color.parseColor("#000000")
labelPaint.color = Color.parseColor("#000000")
typedArray.recycle()
try {
val iStream = URL(imageString)
imageBitmap = BitmapFactory.decodeResource(resources, viewImage) ?: BitmapFactory.decodeStream(iStream.openStream())
}catch (e:Exception){
Log.i("Image", "Kindly provide a valid image")
}
}
override fun onDraw(canvas: Canvas?) {
if(cx == 0f || cy == 0f){
cx = (width/2).toFloat()
cy = (height/2).toFloat()
}
canvas?.drawRect(rect, paint)
canvas?.drawCircle(cx, cy, radius, circlePaint)
if (imageBitmap != null){
canvas?.drawBitmap(imageBitmap!!, 50f, 100f, null)
}
}
}
我还希望能够在运行时在xml之外更改此值,比如在活动或片段中使其成为动态的。
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val url =
"https://dyl80ryjxr1ke.cloudfront.net/external_assets/hero_examples/hair_beach_v1785392215/original.jpeg"
customView.imageString = url
}
}
发布于 2020-07-07 14:39:17
在类CustomView中,将init function中的代码行设置为如下所示的函数:
class CustomView(context: Context, attrSet: AttributeSet) : View(context) {
//setups
init()
{
setupFunction(imageString)
}
fun setupFunction(url: String) {
paint.color = viewColor
circlePaint.color = Color.parseColor("#000000")
labelPaint.color = Color.parseColor("#000000")
typedArray.recycle()
try {
val iStream = URL(imageString)
imageBitmap = BitmapFactory.decodeResource(resources, viewImage)
?: BitmapFactory.decodeStream(iStream.openStream())
} catch (e: Exception) {
Log.i("Image", "Kindly provide a valid image")
}
}
onDraw()
}
现在,您可以在每次需要时从您的片段或活动调用setupFunction(),如下所示:
customView.setupFunction(url)
视图将按您所需的方式启动。
https://stackoverflow.com/questions/62769158
复制相似问题