2012-02-26 7 views
18

soy un programador con un fondo ventanas y soy nuevo en Java y cosas androide,Conseguir tamaño imageview para la creación de mapa de bits

Quiero crear un widget (no una aplicación), que muestra un gráfico.

después de una larga investigación, sé que puedo hacer esto con Canvas, imageviews y Bitmaps.

el lienzo que pinto debe ser el mismo que el tamaño del widget.

así que la pregunta es: ¿Cómo puedo saber el tamaño widgets (o el tamaño imageview) de modo que pueda suministrarla a la función

Bitmap.createBitmap (width_xx, height_yy, Config.ARGB_8888);

Fragmento de código: en el método contador de tiempo de ejecución:

@Override 
    public void run() { 
     Bitmap bitmap = Bitmap.createBitmap(??, ??, Config.ARGB_8888); 
     Canvas canvas = new Canvas(bitmap); 

     //create new paint 
     Paint p = new Paint(); 
     p.setAntiAlias(true); 
     p.setStrokeWidth(1); 

     //draw circle 
     //here i can use the width and height to scale the circle 
     canvas.drawCircle(50, 50, 7, p); 
     remoteViews.setImageViewBitmap(R.id.imageView, bitmap); 
+0

\ * facepalm \ *, un [* App Widget *] (http://developer.android.com/guide/topics/appwidgets/index.html). Dos palabras que, juntas, requieren una respuesta a esta pregunta que no tiene nada que ver con la respuesta que obtendrías en ninguna de ellas. –

+4

Actualmente estoy teniendo el mismo problema. Si ha encontrado una solución al problema, sería genial si la publicara aquí. – flocki

Respuesta

-1

Aquí es un tutoriales hay que ir, todo se da claramente para: Developing Android Home Screen Widgets

+1

gracias por el tutorial, proporciona buena información, pero desafortunadamente no responde mi pregunta, quiero que mi tabla siempre llene el tamaño del widget, independientemente de qué tamaño tenga o qué orientación tenga – Augustus

-2

como Julian dijo, se puede conseguir que el estilo con su imagen de mapa de bits

int width = bitmap.getWidth(); 
int height = bitmap.getHeight(); 
+1

Mire su código de ejemplo. Él quiere * crear * el mapa de bits, y crear el Lienzo que lo usará. Sugiero que espere hasta que .onDraw() proporcione el lienzo. –

+0

sí, Julian tiene razón, el mapa de bits debe crearse según el tamaño de Widget/imageview, espero algo como, int width = widget.getWidth(); o int ancho = imageview.getWidth(); – Augustus

2

por lo que he aprendido, sólo se puede calcular dimensiones de widgets en Android 4.1+. Cuando está en una API inferior, deberá usar dimensiones estáticas. Acerca de las dimensiones de widgets: App Widget Design Guidelines

int w = DEFAULT_WIDTH, h = DEFAULT_HEIGHT; 

if (Build.VERSION.SDK_INT >= 16) { 
    Bundle options = appWidgetManager.getAppWidgetOptions(widgetId); 

    int maxW = options.getInt(AppWidgetManager.OPTION_APPWIDGET_MAX_WIDTH); 
    int maxH = options.getInt(AppWidgetManager.OPTION_APPWIDGET_MAX_HEIGHT); 

    int minW = options.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH); 
    int minH = options.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_HEIGHT); 

    if (context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { 
     w = maxW; 
     h = minH; 
    } else { 
     w = minW; 
     h = maxH; 
    } 
} 
+0

Funciona perfectamente. Felicitaciones por señalar la necesidad de mirar la orientación. Pero, ¿por qué importaría la orientación cuando los valores se llaman "MIN" y "MAX"? – GaryAmundson

0

Actualmente estoy usando esto, creo que sirve

private void run() { 

    int width = 400, height = 400; 

    Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); 
    Canvas c = new Canvas(bitmap); 

    Paint p = new Paint(); 
    p.setColor(Color.WHITE); 
    p.setStyle(Paint.Style.STROKE); 
    p.setStrokeWidth(1); 
    p.setAntiAlias(true); 

    c.drawCircle(width/2, height/2, radius, p); 

    remoteViews.setImageViewBitmap(R.id.imageView, bitmap); 

    ComponentName clockWidget = new ComponentName(context, 
    Clock_22_analog.class); 
    AppWidgetManager appWidgetManager = AppWidgetManager 
    .getInstance(context); 
    appWidgetManager.updateAppWidget(clockWidget, remoteViews); 
} 
0

puede utilizar esta esperanza

Bitmap image1, image2; 

Bitmap bitmap = Bitmap.createBitmap(image1.getWidth(), image1.getHeight(), Bitmap.Config.ARGB_8888); 
Canvas c = new Canvas(bitmap); 

que ayuda. :)

0

u puede crear a medida widget..and establecer el tamaño de Wight en su onMeasure() method..and también guardar el tamaño en ese momento por lo que se puede utilizar para la creación de la imagen más .. Hop

2

Tenga una mirada en el método:

public void onAppWidgetOptionsChanged (Context context, AppWidgetManager appWidgetManager, int appWidgetId, Bundle newOptions) 

se va a llamar cada vez que inicie/cambiar el tamaño del widget.

Getting el widget anchura/altura se puede hacer de la siguiente manera:

newOptions.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH) 
newOptions.getInt(AppWidgetManager.OPTION_APPWIDGET_MAX_WIDTH) 
newOptions.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_HEIGHT) 
newOptions.getInt(AppWidgetManager.OPTION_APPWIDGET_MAX_HEIGHT) 

Vamos a saber si esto responde a su pregunta.

0

No he trabajado en Widgets, pero tengo cierta experiencia en obtener el tamaño de ImageView.

Aquí hay un código que utilizo:

public class ViewSizes { 
    public int width; 
    public int height; 

    public boolean isEmpty() { 
     boolean result = false; 
     if (0 >= width || 0 >= height) { 
      result = true; 
     } 
     return result; 
    } 
} 

Eso es sólo una clase ficticia que contiene los parámetros de tamaño.

public static ViewSizes getSizes(View view) { 
     ViewSizes sizes = new ViewSizes(); 
     sizes.width = view.getWidth(); 
     sizes.height = view.getHeight(); 

     if (sizes.isEmpty()) { 
      LayoutParams params = view.getLayoutParams(); 
      if (null != params) { 
       int widthSpec = View.MeasureSpec.makeMeasureSpec(params.width, View.MeasureSpec.AT_MOST); 
       int heightSpec = View.MeasureSpec.makeMeasureSpec(params.height, View.MeasureSpec.AT_MOST); 
       view.measure(widthSpec, heightSpec); 
      } 

      sizes.width = view.getMeasuredWidth(); 
      sizes.height = view.getMeasuredHeight(); 
     } 

     return sizes; 
    } 

Este método calcula el ancho que forzará un ciclo de medida si aún no sucedió.

public static boolean loadPhoto(ImageView view, String url, float aspectRatio) { 
    boolean processed = false; 
    ViewSizes sizes = ViewsUtils.getSizes(view); 

    if (!sizes.isEmpty()) { 
     int width = sizes.width - 2; 
     int height = sizes.height - 2; 
     if (ASPECT_RATIO_UNDEFINED != aspectRatio) { 
      if (height * aspectRatio > width) { 
       height = (int) (width/aspectRatio); 
      } else if (height * aspectRatio < width) { 
       width = (int) (height * aspectRatio); 
      } 
     } 

     // Do you bitmap processing here 

     processed = true; 
    } 

    return processed; 
} 

Probablemente este sea inútil para usted. Doy solo un ejemplo: tengo una ImageView y url de imagen, que deben ser parametrizados con la imagen y la altura.

public class PhotoLayoutListener implements OnGlobalLayoutListener { 
    private ImageView view; 
    private String url; 
    private float aspectRatio; 


    public PhotoLayoutListener(ImageView view, String url, float aspectRatio) { 
     this.view = view; 
     this.url = url; 
     this.aspectRatio = aspectRatio; 
    } 

    boolean handled = false; 
    @Override 
    public void onGlobalLayout() { 
     if (!handled) { 
      PhotoUtils.loadPhoto(view, url, aspectRatio); 
      handled = true; 
     } 

     ViewTreeObserver viewTreeObserver = view.getViewTreeObserver(); 
     if (viewTreeObserver.isAlive()) { 
      if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { 
       removeLayoutListenerPre16(viewTreeObserver, this); 
      } else { 
       removeLayoutListenerPost16(viewTreeObserver, this); 
      } 
     } 
    } 

    @SuppressWarnings("deprecation") 
    private void removeLayoutListenerPre16(ViewTreeObserver observer, OnGlobalLayoutListener listener){ 
     observer.removeGlobalOnLayoutListener(listener); 
    } 

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN) 
    private void removeLayoutListenerPost16(ViewTreeObserver observer, OnGlobalLayoutListener listener){ 
     observer.removeOnGlobalLayoutListener(listener); 
    } 
} 

Esto es sólo un oyente diseño - Quiero procesar la carga de imágenes una vez que la fase de diseño ha terminado.

public static void setImage(ImageView view, String url, boolean forceLayoutLoading, float aspectRatio) { 
    if (null != view && null != url) { 
     final ViewTreeObserver viewTreeObserver = view.getViewTreeObserver(); 

     if (forceLayoutLoading || !PhotoUtils.loadPhoto(view, url, aspectRatio)) { 
      if (viewTreeObserver.isAlive()) { 
       viewTreeObserver.addOnGlobalLayoutListener(new PhotoLayoutListener(view, url, aspectRatio)); 
      } 
     } 
    } 
} 

Este es el método que realmente llamo. Le doy la vista y la URL. Los métodos se encargan de la carga: si puede determinar el tamaño de la vista, comienza a cargarse inmediatamente. De lo contrario, simplemente asigna un oyente de diseño e inicia el proceso de carga una vez que el diseño finaliza.

Podría quitar algunos parámetros: forceLoading/aspectRatio no debería ser relevante para usted. Después de eso, cambie el método PhotoUtils.loadPhoto para crear el mapa de bits con el ancho/alto que ha calculado.

Cuestiones relacionadas