开发者

Rotate ImageView in widget

I'm creating a widget where I need to rotate an ImageView. The ImageView resides insides a layout which in turn is described in a RemoteView. Is this possible? In my regular application Activity gained a reference to the ImageView using findViewById() and then calling setRotate(), but as RemoteView isn't an activity findViewById() isn't available.

I can see that it has been done before in this app: https://开发者_如何学编程market.android.com/details?id=com.lanteanstudio.compass


If you are using RemoteViews, then you cannot directly change the visible View itself, as there is no way of getting a reference to it -- a RemoteViews object generally runs in a different process (in the case of the widgets on the Homescreen this is true - the widgets run in the Homescreen process, not your own).

Instead you need to create a new RemoteViews with the image rotated - you need to rotate the bitmap before setting it to the ImageView.

Then get an instance of AppWidgetManager, and call manager.updateAppWidget(appWidgetId, remoteView).


After spending a day on this... I found the following code to work for my weather app widget to indicate wind direction.

  • R.drawable.arrow is png in my drawable folder

  • windDeg is an int obtained from openweathermap.org

  • R.id.wind_direction is an ImageView

     val bmpOriginal: Bitmap = BitmapFactory.decodeResource(context.applicationContext.resources,         R.drawable.arrow)
     val bmpResult = Bitmap.createBitmap(bmpOriginal.width, bmpOriginal.height, Bitmap.Config.ARGB_8888)
     val tempCanvas = Canvas(bmpResult)
     tempCanvas.rotate(windDeg.toFloat(), bmpOriginal.width / 2.toFloat(), bmpOriginal.height / 2.toFloat())
     tempCanvas.drawBitmap(bmpOriginal, 0f, 0f, null)
     views.setImageViewBitmap(R.id.wind_direction, bmpResult)
    
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜