private Bitmap drawTextToBitmap(String gText) {
    Bitmap bitmap = Bitmap.createBitmap(500, 500, Bitmap.Config.ARGB_8888);
    bitmap.eraseColor(Color.TRANSPARENT);
    bitmap.setHasAlpha(true);

    //        bitmap.setHasAlpha(true);
    Canvas canvas = new Canvas(bitmap);
    canvas.drawColor(Color.TRANSPARENT);

    TextPaint textPaint = new TextPaint();
    textPaint.setColor(Color.GREEN);
    textPaint.setTextSize(35);
    RectF rect = new RectF(0, 0, 300, 300);
    StaticLayout sl =
        new StaticLayout(
            gText, textPaint, (int) rect.width(), Layout.Alignment.ALIGN_NORMAL, 1, 1, false);
    canvas.save();
    sl.draw(canvas);
    canvas.restore();

    // Flip the image.
    Matrix m = new Matrix();
    m.preScale(-1, 1);
    Bitmap output =
        Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), m, false);
    output.setDensity(DisplayMetrics.DENSITY_DEFAULT);

    return output;
  }
 public void buildCache(int w, int h, int density, boolean checkSizeEquals) {
   boolean reuse = checkSizeEquals ? (w == width && h == height) : (w <= width && h <= height);
   if (reuse && bitmap != null && !bitmap.isRecycled()) {
     //            canvas.drawColor(Color.TRANSPARENT);
     canvas.setBitmap(null);
     bitmap.eraseColor(Color.TRANSPARENT);
     canvas.setBitmap(bitmap);
     recycleBitmapArray();
     return;
   }
   if (bitmap != null) {
     recycle();
   }
   width = w;
   height = h;
   bitmap = NativeBitmapFactory.createBitmap(w, h, Bitmap.Config.ARGB_8888);
   if (density > 0) {
     mDensity = density;
     bitmap.setDensity(density);
   }
   if (canvas == null) {
     canvas = new Canvas(bitmap);
     canvas.setDensity(density);
   } else canvas.setBitmap(bitmap);
 }
Пример #3
0
 private Bitmap flip(Bitmap src) {
   Matrix flipper = new Matrix();
   flipper.preScale(-1, 1);
   Bitmap dst = Bitmap.createBitmap(src, 0, 0, src.getWidth(), src.getHeight(), flipper, false);
   dst.setDensity(DisplayMetrics.DENSITY_DEFAULT);
   return dst;
 }
Пример #4
0
  private Bitmap prepare(final Bitmap map) {
    int dstW = request.getRequiredWidth(), dstH = request.getRequiredHeight();
    if (dstW <= 0 || dstH <= 0 || request.isSkipScaleBeforeMemCache()) {
      if (imagesManager.debug) {
        Log.d(
            TAG,
            "Skip scaling for "
                + request.getKey()
                + " skip flag: "
                + request.isSkipScaleBeforeMemCache());
      }
      return map;
    }

    final int w = map.getWidth(), h = map.getHeight();

    if (w <= dstW && h <= dstH) {
      return map;
    }

    final double ratio = (double) w / h;
    if (w > h) {
      dstH = (int) (dstW / ratio);
    } else {
      dstW = (int) (dstH * ratio);
    }

    if (dstW <= 0 || dstH <= 0) {
      return map;
    }

    final Bitmap scaled = Bitmap.createScaledBitmap(map, dstW, dstH, true);
    scaled.setDensity(imagesManager.getResources().getDisplayMetrics().densityDpi);
    return scaled;
  }
  /**
   * Load a picture from the resource.
   *
   * @param resources
   * @param resourceId
   * @return
   */
  public static Bitmap loadBitmapFromResource(Resources resources, int resourceId) {
    // Not scale the bitmap. This will turn the bitmap in raw pixel unit.
    Options options = new BitmapFactory.Options();
    options.inScaled = false;
    // Load the bitmap object.
    Bitmap bitmap = BitmapFactory.decodeResource(resources, resourceId, options);
    // Set the density to NONE. This is needed for the ImageView to not scale.
    bitmap.setDensity(Bitmap.DENSITY_NONE);

    return bitmap;
  }
Пример #6
0
 @Test
 @org.robolectric.annotation.Config(
     sdk = {
       Build.VERSION_CODES.JELLY_BEAN_MR1,
       Build.VERSION_CODES.JELLY_BEAN_MR2,
       Build.VERSION_CODES.KITKAT,
       Build.VERSION_CODES.LOLLIPOP
     })
 public void shouldSetDensity() {
   final Bitmap bitmap = Bitmap.createBitmap(new DisplayMetrics(), 100, 100, Config.ARGB_8888);
   bitmap.setDensity(1000);
   assertThat(bitmap.getDensity()).isEqualTo(1000);
 }
Пример #7
0
  /**
   * Snapshot a view into a Bitmap with the indicated background color.
   *
   * @param view The target {@link android.view.View}.
   * @param backgroundColor The background color of the Bitmap. If the view has transparency areas,
   *     these areas will be erased using this color.
   * @return Returns a Bitmap containing the view content, or {@code null} if any error occurs. Make
   *     sure to call {@link android.graphics.Bitmap#recycle()} as soon as possible, once its
   *     content is not needed anymore.
   */
  public Bitmap snapshotView(View view, int backgroundColor) {
    if (view == null) {
      return null;
    }

    int viewWidth = view.getRight() - view.getLeft();
    int viewHeight = view.getBottom() - view.getTop();

    int sampleWidth = viewWidth / mSampleSize;
    int sampleHeight = viewHeight / mSampleSize;
    float canvasScale = 1.f / mSampleSize;

    sampleWidth = sampleWidth > 0 ? sampleWidth : 1;
    sampleHeight = sampleHeight > 0 ? sampleHeight : 1;

    performanceTickBegin(
        "snapshotView "
            + view
            + " sampleSize = "
            + mSampleSize
            + " ("
            + sampleWidth
            + ", "
            + sampleHeight
            + "): ");

    Bitmap bitmap = Bitmap.createBitmap(sampleWidth, sampleHeight, Bitmap.Config.ARGB_8888);
    if (bitmap == null) {
      throw new OutOfMemoryError();
    }
    if ((backgroundColor & 0xff000000) != 0) {
      bitmap.eraseColor(backgroundColor);
    }

    bitmap.setDensity(mDisplayMetrics.densityDpi);

    Canvas canvas = new Canvas(bitmap);
    canvas.scale(view.getScaleX() * canvasScale, view.getScaleY() * canvasScale);
    canvas.translate(-view.getScrollX(), -view.getScrollY());

    view.computeScroll();
    view.draw(canvas);

    canvas.setBitmap(null);

    performanceTickEnd();

    return bitmap;
  }
Пример #8
0
  public static Bitmap drawableToBitmap(Drawable drawable) throws IllegalArgumentException {
    if (drawable instanceof BitmapDrawable) {
      return ((BitmapDrawable) drawable).getBitmap();
    }
    Bitmap bitmap;

    try {
      bitmap = Bitmap.createBitmap(1, 80, Config.ARGB_8888);
      bitmap.setDensity(480);
      Canvas canvas = new Canvas(bitmap);
      drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
      drawable.draw(canvas);
    } catch (IllegalArgumentException e) {
      throw e;
    }

    return bitmap;
  }
Пример #9
0
  /*
   * Constructs a BouncyBalloonArea. Note that the list of barriers
   * here should not be the same list that the BarrierManager uses
   * because this is not synchronized.
   */
  public BouncyBalloonArea(Context context, List<BouncyBalloon> balloons) {
    super(context);

    mBalloons = balloons;
    mBarriers = new ArrayList<BouncyBarrier>();
    // Create the paint settings
    mBlackPaint = new Paint();
    mBlackPaint.setColor(Color.BLACK);
    mWhitePaint = new Paint();
    mWhitePaint.setColor(Color.WHITE);
    mWhitePaint.setTextSize(30);
    mWhitePaint.setTextAlign(Align.CENTER);

    // Get the bitmap from the drawable
    BitmapFactory.Options ops = new BitmapFactory.Options();
    mExplosion = BitmapFactory.decodeResource(context.getResources(), R.drawable.explosion, ops);
    mExplosion.setDensity(Bitmap.DENSITY_NONE);
  }
 @SuppressLint("NewApi")
 public void splitWith(
     int dispWidth, int dispHeight, int maximumCacheWidth, int maximumCacheHeight) {
   recycleBitmapArray();
   if (width <= 0 || height <= 0 || bitmap == null || bitmap.isRecycled()) {
     return;
   }
   if (width <= maximumCacheWidth && height <= maximumCacheHeight) {
     return;
   }
   maximumCacheWidth = Math.min(maximumCacheWidth, dispWidth);
   maximumCacheHeight = Math.min(maximumCacheHeight, dispHeight);
   int xCount = width / maximumCacheWidth + (width % maximumCacheWidth == 0 ? 0 : 1);
   int yCount = height / maximumCacheHeight + (height % maximumCacheHeight == 0 ? 0 : 1);
   int averageWidth = width / xCount;
   int averageHeight = height / yCount;
   final Bitmap[][] bmpArray = new Bitmap[yCount][xCount];
   if (canvas == null) {
     canvas = new Canvas();
     if (mDensity > 0) {
       canvas.setDensity(mDensity);
     }
   }
   Rect rectSrc = new Rect();
   Rect rectDst = new Rect();
   for (int yIndex = 0; yIndex < yCount; yIndex++) {
     for (int xIndex = 0; xIndex < xCount; xIndex++) {
       Bitmap bmp =
           bmpArray[yIndex][xIndex] =
               NativeBitmapFactory.createBitmap(
                   averageWidth, averageHeight, Bitmap.Config.ARGB_8888);
       if (mDensity > 0) {
         bmp.setDensity(mDensity);
       }
       canvas.setBitmap(bmp);
       int left = xIndex * averageWidth, top = yIndex * averageHeight;
       rectSrc.set(left, top, left + averageWidth, top + averageHeight);
       rectDst.set(0, 0, bmp.getWidth(), bmp.getHeight());
       canvas.drawBitmap(bitmap, rectSrc, rectDst, null);
     }
   }
   canvas.setBitmap(bitmap);
   bitmapArray = bmpArray;
 }
Пример #11
0
  /**
   * Snapshot sub surfaces of the screen framebuffer into a bitmap.
   *
   * <p>If the minLayer and maxLayer are both zero, it will sample all the surfaces of the screen.
   *
   * @param minLayer The lowest (bottom-most Z order) window surface to include in the screen
   *     snapshot. The possible values are defined in the {@link
   *     android.view.WindowManager.LayoutParams}. Any other values are treated as {@link
   *     android.view.WindowManager.LayoutParams#TYPE_WALLPAPER}.
   * @param maxLayer The highest (top-most z order) window surface to include in the screen
   *     snapshot. The possible values are defined in the {@link
   *     android.view.WindowManager.LayoutParams}. Any other values are treated as {@link
   *     android.view.WindowManager.LayoutParams#TYPE_WALLPAPER}.
   * @return Returns a Bitmap containing the screen contents, or {@code null} if an error occurs.
   *     Make sure to call {@link android.graphics.Bitmap#recycle()} as soon as possible, once its
   *     content is not needed anymore.
   */
  public Bitmap snapshotScreen(int minLayer, int maxLayer) {
    int sampleWidth = mScreenWidth / mSampleSize;
    int sampleHeight = mScreenHeight / mSampleSize;

    sampleWidth = sampleWidth > 0 ? sampleWidth : 1;
    sampleHeight = sampleHeight > 0 ? sampleHeight : 1;

    int minZ = windowTypeToLayerZ(minLayer) * TYPE_LAYER_MULTIPLIER;
    int maxZ = windowTypeToLayerZ(maxLayer) * TYPE_LAYER_MULTIPLIER;

    Bitmap result = null;
    try {
      performanceTickBegin(
          "snapshotScreen(" + sampleWidth + ", " + sampleHeight + "," + minZ + ", " + maxZ + "): ");

      if (Build.VERSION.SDK_INT >= 18) {
        if (minZ == 0 && maxZ == 0) {
          result = surfaceControlScreenshot(sampleWidth, sampleHeight);
        } else {
          result = surfaceControlScreenshotLayer(sampleWidth, sampleHeight, minZ, maxZ);
        }
      } else {
        if (minZ == 0 && maxZ == 0) {
          result = surfaceScreenshot(sampleWidth, sampleHeight);
        } else {
          result = surfaceScreenshotLayer(sampleWidth, sampleHeight, minZ, maxZ);
        }
      }

      result.setDensity(mDisplayMetrics.densityDpi);

      performanceTickEnd();

    } catch (Exception e) {
      // throw new RuntimeException(e.getMessage());
      result = Bitmap.createBitmap(sampleWidth, sampleHeight, Bitmap.Config.ARGB_8888);
      result.eraseColor(Color.WHITE);
      Log.e(TAG, "snapshotScreen failed width exception: " + e.getMessage());
    }

    return result;
  }
Пример #12
0
  private View createButton(Map<Object, Object> hash) {
    Context ctx = RhodesActivity.getContext();

    Object actionObj = hash.get("action");
    if (actionObj == null || !(actionObj instanceof String))
      throw new IllegalArgumentException("'action' should be String");

    String action = (String) actionObj;
    if (action.length() == 0) throw new IllegalArgumentException("'action' should not be empty");

    Drawable icon = null;
    String label = null;
    View.OnClickListener onClick = null;

    if (action.equalsIgnoreCase("back")) {
      icon = ctx.getResources().getDrawable(AndroidR.drawable.back);
      onClick = new ActionBack();
    } else if (action.equalsIgnoreCase("forward")) {
      if (RhodesService.isJQTouch_mode()) {
        return null;
      }
      icon = ctx.getResources().getDrawable(AndroidR.drawable.next);
      onClick = new ActionForward();
    } else if (action.equalsIgnoreCase("home")) {
      icon = ctx.getResources().getDrawable(AndroidR.drawable.home);
      onClick = new ActionHome();
    } else if (action.equalsIgnoreCase("options")) {
      icon = ctx.getResources().getDrawable(AndroidR.drawable.options);
      onClick = new ActionOptions();
    } else if (action.equalsIgnoreCase("refresh")) {
      icon = ctx.getResources().getDrawable(AndroidR.drawable.refresh);
      onClick = new ActionRefresh();
    } else if (action.equalsIgnoreCase("close") || action.equalsIgnoreCase("exit")) {
      icon = ctx.getResources().getDrawable(AndroidR.drawable.exit);
      onClick = new ActionExit();
    } else if (action.equalsIgnoreCase("separator")) return null;

    DisplayMetrics metrics = new DisplayMetrics();
    WindowManager wm = (WindowManager) ctx.getSystemService(Context.WINDOW_SERVICE);
    wm.getDefaultDisplay().getMetrics(metrics);

    Object iconObj = hash.get("icon");
    if (iconObj != null) {
      if (!(iconObj instanceof String))
        throw new IllegalArgumentException("'icon' should be String");
      String iconPath = "apps/" + (String) iconObj;
      iconPath = RhoFileApi.normalizePath(iconPath);
      Bitmap bitmap = BitmapFactory.decodeStream(RhoFileApi.open(iconPath));
      if (bitmap == null) throw new IllegalArgumentException("Can't find icon: " + iconPath);
      bitmap.setDensity(DisplayMetrics.DENSITY_MEDIUM);
      icon = new BitmapDrawable(bitmap);
    }

    if (icon == null) {
      Object labelObj = hash.get("label");
      if (labelObj == null || !(labelObj instanceof String))
        throw new IllegalArgumentException("'label' should be String");
      label = (String) labelObj;
    }

    if (icon == null && label == null)
      throw new IllegalArgumentException("One of 'icon' or 'label' should be specified");

    if (onClick == null) onClick = new ActionCustom(action);

    View button;
    if (icon != null) {
      ImageButton btn = new ImageButton(ctx);
      btn.setImageDrawable(icon);
      button = btn;
      if (mCustomBackgroundColorEnable) {
        Drawable d = btn.getBackground();
        if (d != null) {
          d.setColorFilter(mCustomBackgroundColor, android.graphics.PorterDuff.Mode.SRC_OVER);
        } else {
          btn.setBackgroundColor(mCustomBackgroundColor);
        }
      }
    } else {
      Button btn = new Button(ctx);
      btn.setText(label);
      if (mCustomBackgroundColorEnable) {
        btn.setBackgroundColor(mCustomBackgroundColor);
        int gray =
            (((mCustomBackgroundColor & 0xFF0000) >> 16)
                    + ((mCustomBackgroundColor & 0xFF00) >> 8)
                    + ((mCustomBackgroundColor & 0xFF)))
                / 3;
        if (gray > 128) {
          btn.setTextColor(0xFF000000);
        } else {
          btn.setTextColor(0xFFFFFFFF);
        }
      }
      button = btn;
    }

    button.setOnClickListener(onClick);

    return button;
  }
Пример #13
0
  @SuppressWarnings("unchecked")
  public TabbedMainView(Object params) {
    Context ctx = RhodesActivity.getContext();

    mBackgroundColorEnable = false;

    Vector<Object> tabs = null;
    boolean place_tabs_bottom = false;
    if (params instanceof Vector<?>) tabs = (Vector<Object>) params;
    else if (params instanceof Map<?, ?>) {
      Map<Object, Object> settings = (Map<Object, Object>) params;

      Object bkgObj = settings.get("background_color");
      if ((bkgObj != null) && (bkgObj instanceof String)) {
        int color = Integer.parseInt((String) bkgObj) | 0xFF000000;
        mBackgroundColor = color;
        mBackgroundColorEnable = true;
      }

      Object callbackObj = settings.get("on_change_tab_callback");
      if ((callbackObj != null) && (callbackObj instanceof String)) {
        mChangeTabCallback = new String(((String) callbackObj));
      }

      Object placeBottomObj = settings.get("place_tabs_bottom");
      if ((placeBottomObj != null) && (placeBottomObj instanceof String)) {
        place_tabs_bottom = ((String) placeBottomObj).equalsIgnoreCase("true");
      }

      Object tabsObj = settings.get("tabs");
      if (tabsObj != null && (tabsObj instanceof Vector<?>)) tabs = (Vector<Object>) tabsObj;
    }

    if (tabs == null) throw new IllegalArgumentException("No tabs specified");

    int size = tabs.size();

    host = new TabHost(ctx, null);

    tabData = new Vector<TabData>(size);
    tabIndex = 0;

    TabWidget tabWidget = new TabWidget(ctx);
    tabWidget.setId(android.R.id.tabs);

    FrameLayout frame = new FrameLayout(ctx);
    FrameLayout.LayoutParams lpf = null;
    TabHost.LayoutParams lpt = null;
    if (place_tabs_bottom) {
      frame.setId(android.R.id.tabcontent);
      lpf =
          new FrameLayout.LayoutParams(
              LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, Gravity.TOP);
      host.addView(frame, lpf);

      lpt =
          new TabHost.LayoutParams(
              LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT, Gravity.BOTTOM);
      host.addView(tabWidget, lpt);
    } else {
      lpt =
          new TabHost.LayoutParams(
              LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT, Gravity.TOP);
      host.addView(tabWidget, lpt);

      frame = new FrameLayout(ctx);
      frame.setId(android.R.id.tabcontent);
      lpf =
          new FrameLayout.LayoutParams(
              LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, Gravity.BOTTOM);
      host.addView(frame, lpf);
    }

    host.setup();

    TabHost.TabSpec spec;
    DisplayMetrics metrics = new DisplayMetrics();
    WindowManager wm = (WindowManager) ctx.getSystemService(Context.WINDOW_SERVICE);
    wm.getDefaultDisplay().getMetrics(metrics);

    int selected_color = 0;
    boolean selected_color_enable = false;

    for (int i = 0; i < size; ++i) {
      Object param = tabs.elementAt(i);
      if (!(param instanceof Map<?, ?>)) throw new IllegalArgumentException("Hash expected");

      Map<Object, Object> hash = (Map<Object, Object>) param;

      Object labelObj = hash.get("label");
      if (labelObj == null || !(labelObj instanceof String))
        throw new IllegalArgumentException("'label' should be String");

      Object actionObj = hash.get("action");

      boolean use_current_view_for_tab = false;
      Object use_current_view_for_tab_Obj = hash.get("use_current_view_for_tab");
      if (use_current_view_for_tab_Obj != null) {
        use_current_view_for_tab = ((String) use_current_view_for_tab_Obj).equalsIgnoreCase("true");
      }

      if (use_current_view_for_tab) {
        actionObj = new String("none");
      }
      if (actionObj == null || !(actionObj instanceof String))
        throw new IllegalArgumentException("'action' should be String");

      String label = (String) labelObj;
      String action = (String) actionObj;
      String icon = null;
      boolean reload = false;
      boolean disabled = false;
      int web_bkg_color = 0xFFFFFFFF;

      Object iconObj = hash.get("icon");
      if (iconObj != null && (iconObj instanceof String)) icon = "apps/" + (String) iconObj;

      Object reloadObj = hash.get("reload");
      if (reloadObj != null && (reloadObj instanceof String))
        reload = ((String) reloadObj).equalsIgnoreCase("true");

      Object selected_color_Obj = hash.get("selected_color");
      if ((selected_color_Obj != null) && (selected_color_Obj instanceof String)) {
        selected_color_enable = true;
        selected_color = Integer.parseInt((String) selected_color_Obj) | 0xFF000000;
      }

      Object disabled_Obj = hash.get("disabled");
      if (disabled_Obj != null && (disabled_Obj instanceof String))
        disabled = ((String) disabled_Obj).equalsIgnoreCase("true");

      Object web_bkg_color_Obj = hash.get("web_bkg_color");
      if (web_bkg_color_Obj != null && (web_bkg_color_Obj instanceof String)) {
        web_bkg_color = Integer.parseInt((String) web_bkg_color_Obj) | 0xFF000000;
      }

      spec = host.newTabSpec(Integer.toString(i));

      // Set label and icon
      BitmapDrawable drawable = null;

      if (icon != null) {
        String iconPath = RhoFileApi.normalizePath(icon);
        Bitmap bitmap = BitmapFactory.decodeStream(RhoFileApi.open(iconPath));
        if (disabled && (bitmap != null)) {
          // replace Bitmap to gray
          bitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true); // prepare mutable bitmap
          int x;
          int y;
          int bw = bitmap.getWidth();
          int bh = bitmap.getHeight();
          int nc = DISABLED_IMG_COLOR & 0xFFFFFF;
          int c;
          for (y = 0; y < bh; y++) {
            for (x = 0; x < bw; x++) {
              c = bitmap.getPixel(x, y);
              c = nc | (c & 0xFF000000);
              bitmap.setPixel(x, y, c);
            }
          }
        }

        if (bitmap != null)
          bitmap.setDensity(DisplayMetrics.DENSITY_MEDIUM); // Bitmap.DENSITY_NONE);
        drawable = new BitmapDrawable(bitmap);
        drawable.setTargetDensity(metrics);
      }
      if (drawable == null) spec.setIndicator(label);
      else spec.setIndicator(label, drawable);

      SimpleMainView view = null;
      if (use_current_view_for_tab) {
        RhodesService r = RhodesService.getInstance();
        MainView mainView = r.getMainView();
        action = mainView.currentLocation(-1);
        view = new SimpleMainView(mainView);
      } else {
        view = new SimpleMainView();
      }
      // Set view factory

      if (web_bkg_color_Obj != null) {
        if (!use_current_view_for_tab) {
          view.setWebBackgroundColor(web_bkg_color);
        }
        host.setBackgroundColor(web_bkg_color);
      }

      TabData data = new TabData();
      data.view = view;
      data.url = action;
      data.reload = reload;

      if (use_current_view_for_tab) {
        data.loaded = true;
        tabIndex = i;
      }

      data.selected_color = selected_color;
      data.selected_color_enabled = selected_color_enable;
      data.disabled = disabled;

      TabViewFactory factory = new TabViewFactory(data);
      spec.setContent(factory);

      tabData.addElement(data);
      host.addTab(spec);
    }

    tabWidget.measure(host.getWidth(), host.getHeight());
    int hh = tabWidget.getMeasuredHeight();
    // if (hh < 64) {
    //	hh = 64;
    // }
    if (place_tabs_bottom) {
      lpf.setMargins(0, 0, 0, hh);
    } else {
      lpf.setMargins(0, hh, 0, 0);
    }
    host.updateViewLayout(frame, lpf);
  }