@Override
 public boolean onTouchEvent(MotionEvent event) {
   switch (event.getAction()) {
     case MotionEvent.ACTION_DOWN:
       mMoveOutside = false;
       mFingerRect = new Rect(getLeft(), getTop(), getRight(), getBottom());
       mTouchPoint.set(Math.round(event.getX()), Math.round(event.getY()));
       mState = StateTouchDown;
       mStartTime = System.currentTimeMillis();
       invalidate();
       break;
     case MotionEvent.ACTION_MOVE:
       if (!mFingerRect.contains(getLeft() + (int) event.getX(), getTop() + (int) event.getY())) {
         mMoveOutside = true;
         mState = StateNormal;
         invalidate();
       }
       break;
     case MotionEvent.ACTION_UP:
       if (!mMoveOutside) {
         mState = StateTouchUp;
         mStartTime = System.currentTimeMillis();
         invalidate();
         performClick();
       }
       break;
     case MotionEvent.ACTION_CANCEL:
       mState = StateNormal;
       invalidate();
       break;
   }
   return true;
 }
Ejemplo n.º 2
0
  // Maps the cropping rectangle from image space to screen space.
  private Rect computeLayout() {

    RectF r = new RectF(mCropRect.left, mCropRect.top, mCropRect.right, mCropRect.bottom);
    mMatrix.mapRect(r);
    return new Rect(
        Math.round(r.left), Math.round(r.top), Math.round(r.right), Math.round(r.bottom));
  }
  /**
   * @brief Calculate the correct aspect ratio bounds.
   * @param bounds Available Space for the element
   * @return Rect with the correct aspect ratio, fitting in available space
   */
  private Rect elementCalculateAspectRatioBounds(Rect bounds) {
    Rect newBounds;

    if ((float) bounds.width() / (float) bounds.height() > getElementAspectRatio()) {
      newBounds = new Rect(bounds.left, bounds.top, 0, bounds.bottom);
      newBounds.right = newBounds.left + Math.round(newBounds.height() * getElementAspectRatio());
    } else {
      newBounds = new Rect(bounds.left, bounds.top, bounds.right, 0);
      newBounds.bottom = newBounds.top + Math.round(newBounds.width() / getElementAspectRatio());
    }

    return newBounds;
  }
 private int changeColorAlpha(int color, float value) {
   int alpha = Math.round(Color.alpha(color) * value);
   int red = Color.red(color);
   int green = Color.green(color);
   int blue = Color.blue(color);
   return Color.argb(alpha, red, green, blue);
 }
  /** @brief update helper function for the polaroid bg layer */
  private void updatePolaroidDrawable(Rect bounds) {
    PDEColor highColor;
    PDEColor lowColor;
    float red, green, blue;
    Rect frameRect = new Rect(0, 0, bounds.width(), bounds.height());

    mElementCornerRadius = bounds.width() * 0.07f;
    // update Frame
    mElementPolaroidDrawable.setBounds(frameRect);
    mElementPolaroidDrawable.setElementCornerRadius(mElementCornerRadius);
    mElementPolaroidDrawable.setElementBorderColor(mElementPolaroidFrameColor);
    // todo: this border stuff does not work properly!!! So we take a workaround.
    // mElementPolaroidDrawable.setElementBorderWidth(polaroidRelativeValue(2.5f));
    int border = Math.round(polaroidRelativeValue(2.5f));
    mElementGradientDrawable.setBounds(
        frameRect.left + border,
        frameRect.top + border,
        frameRect.right - border,
        frameRect.bottom - border);

    red = mElementPolaroidFrameColor.getRed();
    blue = mElementPolaroidFrameColor.getBlue();
    green = mElementPolaroidFrameColor.getGreen();

    highColor = new PDEColor(red, green, blue, 0.0f);
    lowColor = new PDEColor(red - 0.33f, green - 0.33f, blue - 0.33f, 0.75f);
    mElementGradientDrawable.setElementBackgroundGradientColors(highColor, highColor, lowColor);
    mElementGradientDrawable.setElementGradientDistributionPositions(0.0f, 0.85f, 1.0f);

    // set other layer data
    mElementPolaroidDrawable.setElementBackgroundColor(mElementPolaroidFrameColor);
    mElementGradientDrawable.setElementCornerRadius(mElementCornerRadius);
    mElementGradientDrawable.setElementBorderColor(PDEColor.valueOf("DTTransparentBlack"));
  }
Ejemplo n.º 6
0
  public SVGTileProvider(File file, float dpi) throws IOException {
    mScale = Math.round(dpi + .3f); // Make it look nice on N7 (1.3 dpi)
    mDimension = BASE_TILE_SIZE * mScale;

    mPool = new TileGeneratorPool(POOL_MAX_SIZE);

    SVG svg = new SVGBuilder().readFromInputStream(new FileInputStream(file)).build();
    mSvgPicture = svg.getPicture();
    RectF limits = svg.getLimits();

    // These values map the SVG file to world coordinates.
    // See: http://stackoverflow.com/questions/21167584/google-io-2013-app-mystery-values
    mBaseMatrix = new Matrix();
    mBaseMatrix.setPolyToPoly(
        new float[] {
          0,
          0, // North-West
          limits.width(),
          0, // North-East
          limits.width(),
          limits.height() // South-East
        },
        0,
        BuildConfig.MAP_FLOORPLAN_MAPPING,
        0,
        3);
  }
 @TargetApi(Build.VERSION_CODES.HONEYCOMB)
 @SuppressWarnings("deprecation")
 private void setAlpha(ImageView imageView, float alpha) {
   if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
     imageView.setAlpha(alpha);
   } else {
     imageView.setAlpha(Math.round(alpha * 255));
   }
 }
Ejemplo n.º 8
0
 private void drawStatistic(Canvas canvas) {
   renderCount++;
   long diffTime = SystemClock.elapsedRealtime() - lastTime;
   if (diffTime > 1000) {
     speed = Math.round(renderCount * 1000f / diffTime);
     lastTime = SystemClock.elapsedRealtime();
     renderCount = 0;
   }
   canvas.drawText("FPS: " + speed, 30, 100, paintStatistics);
 }
Ejemplo n.º 9
0
  @Override
  public boolean onTouchEvent(MotionEvent event) {
    if (moveAnimation.isActive() || explosionAnimation.isActive()) {
      return true;
    }
    if (event.getAction() != MotionEvent.ACTION_UP) {
      return true; // super.onTouchEvent(event);
    }
    int x = Math.round((event.getX() - dataHolder.getCellSize() / 2) / dataHolder.getCellSize());
    int y = Math.round((event.getY() - dataHolder.getCellSize() / 2) / dataHolder.getCellSize());
    if (x < 0
        || x >= dataHolder.getGameEngine().getGameField().getSizeX()
        || y < 0
        || y >= dataHolder.getGameEngine().getGameField().getSizeY()) {
      return super.onTouchEvent(event);
    } else {
      TouchResult results = dataHolder.getGameEngine().touchAction(x, y);
      switch (results) {
        case explode:
          startExplosion();
          break;

        case selected:
          startSelection();
          break;

        case no_action:
          if (selectionAnimation.isActive()) {
            selectionAnimation.stop();
            invalidate();
          }
          if (moveAnimation.isActive()) {
            moveAnimation.stop();
            invalidate();
          }
          break;
        default:
          break;
      }
    }
    return true;
  }
Ejemplo n.º 10
0
 @Override
 public boolean handleMotionEvent(MotionEvent event) {
   if ((event.getSource() & InputDevice.SOURCE_JOYSTICK) != 0) {
     int actionPointerIndex = event.getActionIndex();
     int action = event.getActionMasked();
     switch (action) {
       case MotionEvent.ACTION_MOVE:
         SDLJoystick joystick = getJoystick(event.getDeviceId());
         if (joystick != null) {
           for (int i = 0; i < joystick.axes.size(); i++) {
             InputDevice.MotionRange range = joystick.axes.get(i);
             /* Normalize the value to -1...1 */
             float value =
                 (event.getAxisValue(range.getAxis(), actionPointerIndex) - range.getMin())
                         / range.getRange()
                         * 2.0f
                     - 1.0f;
             SDLActivity.onNativeJoy(joystick.device_id, i, value);
           }
           for (int i = 0; i < joystick.hats.size(); i += 2) {
             int hatX =
                 Math.round(
                     event.getAxisValue(joystick.hats.get(i).getAxis(), actionPointerIndex));
             int hatY =
                 Math.round(
                     event.getAxisValue(joystick.hats.get(i + 1).getAxis(), actionPointerIndex));
             SDLActivity.onNativeHat(joystick.device_id, i / 2, hatX, hatY);
           }
         }
         break;
       default:
         break;
     }
   }
   return true;
 }
Ejemplo n.º 11
0
  /**
   * Draw the correct gallow image. Calculate the best hangman image, and then search the ID from
   * the resource
   */
  private void drawGallow() {
    double steps =
        (((double) config.DRAW_GALLOW_STEPS) / Hangman.settings.get_tries())
            * (Hangman.settings.get_tries() - Hangman.getLives());
    int nr;
    if (steps < 12) nr = (int) Math.round(steps);
    else if (steps >= 13) nr = 13;
    else nr = 12;

    String HANGMAN = "hangman" + nr;

    int resID = this.getResources().getIdentifier(HANGMAN, "drawable", "com.mprog.hangman");
    gallow = (Bitmap) BitmapFactory.decodeResource(getResources(), resID);
    canvas.drawBitmap(gallow, 0, (45 * scrMlt), null);
  }
    public boolean play(Canvas out, Context context) {
      float aspect = out.getHeight() * 1.0f / out.getWidth();
      int width = 1000;
      Bitmap bitmap = Bitmap.createBitmap(width, Math.round(width * aspect), Bitmap.Config.RGB_565);
      Canvas c = new Canvas(bitmap);
      bounds = c.getClipBounds();
      windowBounds = out.getClipBounds();

      if (paint == null) {
        String currentSize =
            Shared.getOptionAtribute(
                context.getString(R.string.FontSize), getString(R.string.current), context);
        String textColour =
            Shared.getOptionAtribute(
                context.getString(R.string.Colours), getString(R.string.text), context);
        paint = new Paint();
        paint.setColor(
            Color.parseColor(
                Shared.getOption(context.getString(R.string.Colours) + "/" + textColour, context)
                    .getTextContent()));
        paint.setTextSize(
            new Integer(
                Shared.getOption(context.getString(R.string.FontSize) + "/" + currentSize, context)
                    .getTextContent()));
        String font =
            Shared.getOptionAtribute(
                getString(R.string.Font), getString(R.string.current), getApplicationContext());
        Typeface face =
            Typeface.createFromAsset(
                getAssets(),
                Shared.getOption(getString(R.string.Font) + "/" + font, getApplicationContext())
                    .getTextContent());
        paint.setTypeface(face);
      }
      c.drawText("tap the screen", 50, 50, paint);
      c.drawText("to start", 50, 100, paint);
      c.drawText("the test.", 50, 150, paint);
      c.drawText("Pick the Months", 50, 200, paint);
      c.drawText("in reverse order", 50, 250, paint);
      // c.drawText("",50,300,paint);

      out.drawBitmap(bitmap, c.getClipBounds(), out.getClipBounds(), paint);

      return finished;
    }
  private void setFlipDistance(float flipDistance) {

    if (mPageCount < 1) {
      mFlipDistance = 0;
      mCurrentPageIndex = INVALID_PAGE_POSITION;
      mCurrentPageId = -1;
      recycleActiveViews();
      return;
    }

    if (flipDistance == mFlipDistance) {
      return;
    }

    mFlipDistance = flipDistance;

    final int currentPageIndex = (int) Math.round(mFlipDistance / FLIP_DISTANCE_PER_PAGE);

    if (mCurrentPageIndex != currentPageIndex) {
      mCurrentPageIndex = currentPageIndex;
      mCurrentPageId = mAdapter.getItemId(mCurrentPageIndex);

      // TODO be smarter about this. Dont remove a view that will be added
      // again on the next line.
      recycleActiveViews();

      // add the new active views
      if (mCurrentPageIndex > 0) {
        fillPageForIndex(mPreviousPage, mCurrentPageIndex - 1);
        addView(mPreviousPage.v);
      }
      if (mCurrentPageIndex >= 0 && mCurrentPageIndex < mPageCount) {
        fillPageForIndex(mCurrentPage, mCurrentPageIndex);
        addView(mCurrentPage.v);
      }
      if (mCurrentPageIndex < mPageCount - 1) {
        fillPageForIndex(mNextPage, mCurrentPageIndex + 1);
        addView(mNextPage.v);
      }
    }

    invalidate();
  }
Ejemplo n.º 14
0
  public static Bitmap blurBmp(Bitmap bmp, int Blur) {

    int pixels[] = new int[bmp.getWidth() * bmp.getHeight()];
    int pixelsRawSource[] = new int[bmp.getWidth() * bmp.getHeight() * 3];
    int pixelsRawNew[] = new int[bmp.getWidth() * bmp.getHeight() * 3];
    bmp.getPixels(pixels, 0, bmp.getWidth(), 0, 0, bmp.getWidth(), bmp.getHeight());

    for (int k = 1; k <= Blur; k++) {

      for (int i = 0; i < pixels.length; i++) {
        pixelsRawSource[i * 3 + 0] = Color.red(pixels[i]);
        pixelsRawSource[i * 3 + 1] = Color.green(pixels[i]);
        pixelsRawSource[i * 3 + 2] = Color.blue(pixels[i]);
      }

      int CurrentPixel = bmp.getWidth() * 3 + 3;
      for (int i = 0; i < bmp.getHeight() - 3; i++) {
        for (int j = 0; j < bmp.getWidth() * 3; j++) {
          CurrentPixel += 1;

          int sumColor = 0;
          sumColor = pixelsRawSource[CurrentPixel - bmp.getWidth() * 3];
          sumColor = sumColor + pixelsRawSource[CurrentPixel - 3];
          sumColor = sumColor + pixelsRawSource[CurrentPixel + 3];
          sumColor = sumColor + pixelsRawSource[CurrentPixel + bmp.getWidth() * 3];
          pixelsRawNew[CurrentPixel] = Math.round(sumColor / 4);
        }
      }

      for (int i = 0; i < pixels.length; i++) {
        pixels[i] =
            Color.rgb(pixelsRawNew[i * 3 + 0], pixelsRawNew[i * 3 + 1], pixelsRawNew[i * 3 + 2]);
      }
    }

    Bitmap bmpReturn = Bitmap.createBitmap(bmp.getWidth(), bmp.getHeight(), Config.ARGB_8888);
    bmpReturn.setPixels(pixels, 0, bmp.getWidth(), 0, 0, bmp.getWidth(), bmp.getHeight());

    return bmpReturn;
  }
Ejemplo n.º 15
0
  public SVGTileProvider(File file, float dpi) throws IOException {
    mScale = Math.round(dpi + .3f); // Make it look nice on N7 (1.3 dpi)
    mDimension = BASE_TILE_SIZE * mScale;

    mPool = new TileGeneratorPool(POOL_MAX_SIZE);

    SVG svg = new SVGBuilder().readFromInputStream(new FileInputStream(file)).build();
    mSvgPicture = svg.getPicture();
    RectF limits = svg.getLimits();

    mBaseMatrix = new Matrix();
    mBaseMatrix.setPolyToPoly(
        new float[] {0, 0, limits.width(), 0, limits.width(), limits.height()},
        0,
        new float[] {
          40.95635986328125f, 98.94217824936158f,
          40.95730018615723f, 98.94123077396628f,
          40.95791244506836f, 98.94186019897214f
        },
        0,
        3);
  }
  /** @brief update function for the image layer (image self, image gradient, image inner-shadow) */
  private void updateElementImageDrawable(Rect bounds) {
    PDEColor highColor, mainColor;
    PDEColor lowColor;
    //        float placeHolderFrameDistance;
    Rect imgBounds;

    // int
    //        placeHolderFrameDistance = (bounds.width() - polaroidRelativeValue(176.5f) )/2.0f +
    // Math.round(polaroidRelativeValue(2.5f));
    //        Rect frameRect = new Rect((int)placeHolderFrameDistance,
    // (int)placeHolderFrameDistance,
    //                                  (int)placeHolderFrameDistance +
    // (int)polaroidRelativeValue(176.5f),
    //                                  (int)placeHolderFrameDistance +
    // (int)polaroidRelativeValue(176.5f));
    int border = Math.round(polaroidRelativeValue(2.5f));
    //        Rect frameRect = new Rect(bounds.left + border,bounds.top + border,bounds.right -
    // border,
    //                                  bounds.bottom - border);

    Rect frameRect = new Rect(0, 0, bounds.width(), bounds.height());
    // mElementImageDrawable.enableAspectRatio(false);
    //        mElementImageDrawable.setBounds(frameRect.left + border, frameRect.top + border,
    // frameRect.right - 2 * border,
    //                                        frameRect.right - border);

    mElementImageDrawable.setLayoutOffset(frameRect.left + 2 * border, frameRect.top + 2 * border);
    mElementImageDrawable.setLayoutWidth(frameRect.width() - 4 * border);

    Path clipPath;
    clipPath = new Path();
    float radius = mElementPolaroidDrawable.getElementCornerRadius() - border / 2.0f;
    // calculate clip path
    //        clipPath.addRoundRect(new RectF(mElementImageDrawable.getBounds().left /*+ border*/,
    //                                        mElementImageDrawable.getBounds().top /*+ border*/,
    //                                        mElementImageDrawable.getBounds().right,
    //                                        mElementImageDrawable.getBounds().bottom),radius,
    // radius,
    //                Path.Direction.CW);

    clipPath.addRoundRect(
        new RectF(
            0.5f /*+ border*/,
            0.5f /*+ border*/,
            mElementImageDrawable.getBounds().width() - 0.5f,
            mElementImageDrawable.getBounds().height() - 0.5f),
        radius,
        radius,
        Path.Direction.CW);

    clipPath.close();
    //        mElementImageDrawable.setElementClipPath(clipPath,true);
    mElementImageDrawable.setElementClipPath(clipPath);

    // Add some gradient to the image view.
    highColor = new PDEColor(1.0f, 1.0f, 1.0f, 0.5f);
    mainColor = new PDEColor(0.5f, 0.5f, 0.5f, 0.25f);
    lowColor = new PDEColor(0.0f, 0.0f, 0.0f, 0.0f);

    //        highColor = new PDEColor(1.0f,0.0f,0.0f,0.5f);
    //        mainColor = new PDEColor(1.0f,0.0f,0.0f,0.5f);
    //        lowColor = new PDEColor(1.0f,0.0f,0.0f,0.5f);

    imgBounds = mElementImageDrawable.getBounds();
    mElementImageGradientDrawable.setLayoutRect(
        new Rect(imgBounds.left - 1, imgBounds.top - 1, imgBounds.right + 1, imgBounds.bottom + 1));

    mElementImageGradientDrawable.setElementBorderColor(PDEColor.valueOf("DTTransparentBlack"));
    mElementImageGradientDrawable.setElementCornerRadius(radius);
    mElementImageGradientDrawable.setElementBackgroundGradientColors(
        highColor, mainColor, lowColor);

    // set inner shadow on image
    mElementInnerShadowDrawable.setElementBlurRadius(polaroidRelativeValue(8.0f));
    /*        RectF layoutRect = new RectF(mElementImageDrawable.getBounds().left, mElementImageDrawable.getBounds().top,
    mElementImageDrawable.getBounds().right,
    mElementImageDrawable.getBounds().bottom);*/
    mElementInnerShadowDrawable.setLayoutRect(mElementImageGradientDrawable.getBounds());
    mElementInnerShadowDrawable.setElementShapeRoundedRect(radius);
  }
Ejemplo n.º 17
0
  protected void draw(Canvas canvas) {

    if (mHidden) {
      return;
    }

    Path path = new Path();
    if (!hasFocus()) {
      mOutlinePaint.setColor(0xFF000000);
      canvas.drawRect(mDrawRect, mOutlinePaint);
    } else {
      Rect viewDrawingRect = new Rect();
      mContext.getDrawingRect(viewDrawingRect);
      if (mCircle) {

        canvas.save();

        float width = mDrawRect.width();
        float height = mDrawRect.height();
        path.addCircle(
            mDrawRect.left + (width / 2),
            mDrawRect.top + (height / 2),
            width / 2,
            Path.Direction.CW);
        mOutlinePaint.setColor(0xFFEF04D6);
        mOutlinePaint.setColor(0x0a83fe);

        canvas.clipPath(path, Region.Op.DIFFERENCE);
        canvas.drawRect(viewDrawingRect, hasFocus() ? mFocusPaint : mNoFocusPaint);

        canvas.restore();

      } else {

        Rect topRect =
            new Rect(
                viewDrawingRect.left, viewDrawingRect.top, viewDrawingRect.right, mDrawRect.top);
        if (topRect.width() > 0 && topRect.height() > 0) {
          canvas.drawRect(topRect, hasFocus() ? mFocusPaint : mNoFocusPaint);
        }
        Rect bottomRect =
            new Rect(
                viewDrawingRect.left,
                mDrawRect.bottom,
                viewDrawingRect.right,
                viewDrawingRect.bottom);
        if (bottomRect.width() > 0 && bottomRect.height() > 0) {
          canvas.drawRect(bottomRect, hasFocus() ? mFocusPaint : mNoFocusPaint);
        }
        Rect leftRect =
            new Rect(viewDrawingRect.left, topRect.bottom, mDrawRect.left, bottomRect.top);
        if (leftRect.width() > 0 && leftRect.height() > 0) {
          canvas.drawRect(leftRect, hasFocus() ? mFocusPaint : mNoFocusPaint);
        }
        Rect rightRect =
            new Rect(mDrawRect.right, topRect.bottom, viewDrawingRect.right, bottomRect.top);
        if (rightRect.width() > 0 && rightRect.height() > 0) {
          canvas.drawRect(rightRect, hasFocus() ? mFocusPaint : mNoFocusPaint);
        }

        path.addRect(new RectF(mDrawRect), Path.Direction.CW);

        mOutlinePaint.setColor(Color.parseColor("#0a83fe"));
      }

      canvas.drawPath(path, mOutlinePaint);

      if (mMode == ModifyMode.Grow) {
        if (mCircle) {
          int width = mResizeDrawableDiagonal.getIntrinsicWidth();
          int height = mResizeDrawableDiagonal.getIntrinsicHeight();

          int d = (int) Math.round(Math.cos(/* 45deg */ Math.PI / 4D) * (mDrawRect.width() / 2D));
          int x = mDrawRect.left + (mDrawRect.width() / 2) + d - width / 2;
          int y = mDrawRect.top + (mDrawRect.height() / 2) - d - height / 2;
          mResizeDrawableDiagonal.setBounds(
              x,
              y,
              x + mResizeDrawableDiagonal.getIntrinsicWidth(),
              y + mResizeDrawableDiagonal.getIntrinsicHeight());
          mResizeDrawableDiagonal.draw(canvas);
        } else {
          int left = mDrawRect.left + 1;
          int right = mDrawRect.right + 1;
          int top = mDrawRect.top + 4;
          int bottom = mDrawRect.bottom + 3;

          int widthWidth = mResizeDrawableWidth.getIntrinsicWidth() / 2;
          int widthHeight = mResizeDrawableWidth.getIntrinsicHeight() / 2;
          int heightHeight = mResizeDrawableHeight.getIntrinsicHeight() / 2;
          int heightWidth = mResizeDrawableHeight.getIntrinsicWidth() / 2;

          int xMiddle = mDrawRect.left + ((mDrawRect.right - mDrawRect.left) / 2);
          int yMiddle = mDrawRect.top + ((mDrawRect.bottom - mDrawRect.top) / 2);

          mResizeDrawableWidth.setBounds(
              left - widthWidth, yMiddle - widthHeight, left + widthWidth, yMiddle + widthHeight);
          mResizeDrawableWidth.draw(canvas);

          mResizeDrawableWidth.setBounds(
              right - widthWidth, yMiddle - widthHeight, right + widthWidth, yMiddle + widthHeight);
          mResizeDrawableWidth.draw(canvas);

          mResizeDrawableHeight.setBounds(
              xMiddle - heightWidth, top - heightHeight, xMiddle + heightWidth, top + heightHeight);
          mResizeDrawableHeight.draw(canvas);

          mResizeDrawableHeight.setBounds(
              xMiddle - heightWidth,
              bottom - heightHeight,
              xMiddle + heightWidth,
              bottom + heightHeight);
          mResizeDrawableHeight.draw(canvas);
        }
      }
    }
  }
 /**
  * @brief Set height of the element.
  *     <p>Convenience function.
  * @param height The new height of the element.
  */
 @Override
 public void setLayoutHeight(int height) {
   setLayoutSize(new Point(Math.round(height * getElementAspectRatio()), height));
 }
 /**
  * @brief Set width of the element.
  *     <p>Convenience function.
  * @param width The new width of the element.
  */
 @Override
 public void setLayoutWidth(int width) {
   setLayoutSize(new Point(width, Math.round((float) width / getElementAspectRatio())));
 }
 @Override
 protected void onDraw(Canvas canvas) {
   super.onDraw(canvas);
   int radius = 0;
   int shadowColor = changeColorAlpha(mShadowColor, MIN_SHADOW_COLOR_ALPHA);
   long elapsed = System.currentTimeMillis() - mStartTime;
   switch (mState) {
     case StateNormal:
       shadowColor = changeColorAlpha(mShadowColor, MIN_SHADOW_COLOR_ALPHA);
       break;
     case StateTouchDown:
       ripplePaint.setAlpha(255);
       if (elapsed < ANIMATION_DURATION) {
         radius = Math.round(elapsed * getWidth() / 2 / ANIMATION_DURATION);
         float shadowAlpha =
             (MAX_SHADOW_COLOR_ALPHA - MIN_SHADOW_COLOR_ALPHA) * elapsed / ANIMATION_DURATION
                 + MIN_SHADOW_COLOR_ALPHA;
         shadowColor = changeColorAlpha(mShadowColor, shadowAlpha);
       } else {
         radius = getWidth() / 2;
         shadowColor = changeColorAlpha(mShadowColor, MAX_SHADOW_COLOR_ALPHA);
       }
       postInvalidate();
       break;
     case StateTouchUp:
       if (elapsed < ANIMATION_DURATION) {
         int alpha = Math.round((ANIMATION_DURATION - elapsed) * 255 / ANIMATION_DURATION);
         ripplePaint.setAlpha(alpha);
         radius = getWidth() / 2 + Math.round(elapsed * getWidth() / 2 / ANIMATION_DURATION);
         float shadowAlpha =
             (MAX_SHADOW_COLOR_ALPHA - MIN_SHADOW_COLOR_ALPHA)
                     * (ANIMATION_DURATION - elapsed)
                     / ANIMATION_DURATION
                 + MIN_SHADOW_COLOR_ALPHA;
         shadowColor = changeColorAlpha(mShadowColor, shadowAlpha);
       } else {
         mState = StateNormal;
         radius = 0;
         ripplePaint.setAlpha(0);
         shadowColor = changeColorAlpha(mShadowColor, MIN_SHADOW_COLOR_ALPHA);
       }
       postInvalidate();
       break;
   }
   backgroundPaint.setShadowLayer(mShadowRadius, mShadowOffsetX, mShadowOffsetY, shadowColor);
   canvas.drawRoundRect(getRectF(), mCornerRadius, mCornerRadius, backgroundPaint);
   canvas.save();
   if (mState == StateTouchDown || mState == StateTouchUp) {
     if (rippleClipPath == null) {
       rippleClipPath = new Path();
       rippleClipPath.addRoundRect(getRectF(), mCornerRadius, mCornerRadius, Path.Direction.CW);
     }
     canvas.clipPath(rippleClipPath);
   }
   canvas.drawCircle(mTouchPoint.x, mTouchPoint.y, radius, ripplePaint);
   canvas.restore();
   if (mText != null && mText.length() > 0) {
     int y = (int) (getHeight() / 2 - ((textPaint.descent() + textPaint.ascent()) / 2));
     canvas.drawText(mText.toString(), getWidth() / 2, y, textPaint);
   }
 }
 @Override
 public void startElement(String namespaceURI, String localName, String qName, Attributes atts)
     throws SAXException {
   // Reset paint opacity
   paint.setAlpha(255);
   // Ignore everything but rectangles in bounds mode
   if (boundsMode) {
     if (localName.equals("rect")) {
       Float x = getFloatAttr("x", atts);
       if (x == null) {
         x = 0f;
       }
       Float y = getFloatAttr("y", atts);
       if (y == null) {
         y = 0f;
       }
       Float width = getFloatAttr("width", atts);
       Float height = getFloatAttr("height", atts);
       bounds = new RectF(x, y, x + width, y + height);
     }
     return;
   }
   if (localName.equals("svg")) {
     int width = (int) Math.ceil(getFloatAttr("width", atts));
     int height = (int) Math.ceil(getFloatAttr("height", atts));
     canvas = picture.beginRecording(width, height);
   } else if (localName.equals("defs")) {
     // Ignore
   } else if (localName.equals("linearGradient")) {
     gradient = doGradient(true, atts);
   } else if (localName.equals("radialGradient")) {
     gradient = doGradient(false, atts);
   } else if (localName.equals("stop")) {
     if (gradient != null) {
       float offset = getFloatAttr("offset", atts);
       String styles = getStringAttr("style", atts);
       StyleSet styleSet = new StyleSet(styles);
       String colorStyle = styleSet.getStyle("stop-color");
       int color = Color.BLACK;
       if (colorStyle != null) {
         if (colorStyle.startsWith("#")) {
           color = Integer.parseInt(colorStyle.substring(1), 16);
         } else {
           color = Integer.parseInt(colorStyle, 16);
         }
       }
       String opacityStyle = styleSet.getStyle("stop-opacity");
       if (opacityStyle != null) {
         float alpha = Float.parseFloat(opacityStyle);
         int alphaInt = Math.round(255 * alpha);
         color |= (alphaInt << 24);
       } else {
         color |= 0xFF000000;
       }
       gradient.positions.add(offset);
       gradient.colors.add(color);
     }
   } else if (localName.equals("g")) {
     // Check to see if this is the "bounds" layer
     if ("bounds".equalsIgnoreCase(getStringAttr("id", atts))) {
       boundsMode = true;
     }
     if (hidden) {
       hiddenLevel++;
       // Util.debug("Hidden up: " + hiddenLevel);
     }
     // Go in to hidden mode if display is "none"
     if ("none".equals(getStringAttr("display", atts))) {
       if (!hidden) {
         hidden = true;
         hiddenLevel = 1;
         // Util.debug("Hidden up: " + hiddenLevel);
       }
     }
     pushTransform(atts);
   } else if (!hidden && localName.equals("rect")) {
     Float x = getFloatAttr("x", atts);
     if (x == null) {
       x = 0f;
     }
     Float y = getFloatAttr("y", atts);
     if (y == null) {
       y = 0f;
     }
     Float width = getFloatAttr("width", atts);
     Float height = getFloatAttr("height", atts);
     Float rx = getFloatAttr("rx", atts);
     Float ry = getFloatAttr("ry", atts);
     if (rx == null) {
       if (ry == null) rx = ry = 0f;
       else rx = ry;
     } else {
       if (ry == null) ry = rx;
     }
     if (rx > width / 2) rx = width * 0.5f;
     if (ry > height / 2) ry = height * 0.5f;
     pushTransform(atts);
     Properties props = new Properties(atts);
     if (doFill(props, gradientMap)) {
       doLimits(x, y, width, height);
       if (rx > 0 && ry > 0)
         canvas.drawRoundRect(new RectF(x, y, x + width, y + height), rx, ry, paint);
       else canvas.drawRect(x, y, x + width, y + height, paint);
     }
     if (doStroke(props, gradientMap)) {
       if (rx > 0 && ry > 0)
         canvas.drawRoundRect(new RectF(x, y, x + width, y + height), rx, ry, paint);
       else canvas.drawRect(x, y, x + width, y + height, paint);
     }
     popTransform();
   } else if (!hidden && localName.equals("line")) {
     Float x1 = getFloatAttr("x1", atts);
     Float x2 = getFloatAttr("x2", atts);
     Float y1 = getFloatAttr("y1", atts);
     Float y2 = getFloatAttr("y2", atts);
     Properties props = new Properties(atts);
     if (doStroke(props, gradientMap)) {
       pushTransform(atts);
       doLimits(x1, y1);
       doLimits(x2, y2);
       canvas.drawLine(x1, y1, x2, y2, paint);
       popTransform();
     }
   } else if (!hidden && localName.equals("circle")) {
     Float centerX = getFloatAttr("cx", atts);
     Float centerY = getFloatAttr("cy", atts);
     Float radius = getFloatAttr("r", atts);
     if (centerX != null && centerY != null && radius != null) {
       pushTransform(atts);
       Properties props = new Properties(atts);
       if (doFill(props, gradientMap)) {
         doLimits(centerX - radius, centerY - radius);
         doLimits(centerX + radius, centerY + radius);
         canvas.drawCircle(centerX, centerY, radius, paint);
       }
       if (doStroke(props, gradientMap)) {
         canvas.drawCircle(centerX, centerY, radius, paint);
       }
       popTransform();
     }
   } else if (!hidden && localName.equals("ellipse")) {
     Float centerX = getFloatAttr("cx", atts);
     Float centerY = getFloatAttr("cy", atts);
     Float radiusX = getFloatAttr("rx", atts);
     Float radiusY = getFloatAttr("ry", atts);
     if (centerX != null && centerY != null && radiusX != null && radiusY != null) {
       pushTransform(atts);
       Properties props = new Properties(atts);
       rect.set(centerX - radiusX, centerY - radiusY, centerX + radiusX, centerY + radiusY);
       if (doFill(props, gradientMap)) {
         doLimits(centerX - radiusX, centerY - radiusY);
         doLimits(centerX + radiusX, centerY + radiusY);
         canvas.drawOval(rect, paint);
       }
       if (doStroke(props, gradientMap)) {
         canvas.drawOval(rect, paint);
       }
       popTransform();
     }
   } else if (!hidden && (localName.equals("polygon") || localName.equals("polyline"))) {
     NumberParse numbers = getNumberParseAttr("points", atts);
     if (numbers != null) {
       Path p = new Path();
       ArrayList<Float> points = numbers.numbers;
       if (points.size() > 1) {
         pushTransform(atts);
         Properties props = new Properties(atts);
         p.moveTo(points.get(0), points.get(1));
         for (int i = 2; i < points.size(); i += 2) {
           float x = points.get(i);
           float y = points.get(i + 1);
           p.lineTo(x, y);
         }
         // Don't close a polyline
         if (localName.equals("polygon")) {
           p.close();
         }
         if (doFill(props, gradientMap)) {
           doLimits(p);
           canvas.drawPath(p, paint);
         }
         if (doStroke(props, gradientMap)) {
           canvas.drawPath(p, paint);
         }
         popTransform();
       }
     }
   } else if (!hidden && localName.equals("path")) {
     Path p = doPath(getStringAttr("d", atts));
     pushTransform(atts);
     Properties props = new Properties(atts);
     if (doFill(props, gradientMap)) {
       doLimits(p);
       canvas.drawPath(p, paint);
     }
     if (doStroke(props, gradientMap)) {
       canvas.drawPath(p, paint);
     }
     popTransform();
   } else if (!hidden) {
     //                Log.d(TAG, "UNRECOGNIZED SVG COMMAND: " + localName);
   }
 }
  @Override
  protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    final int widthMode = MeasureSpec.getMode(widthMeasureSpec);
    final int heightMode = MeasureSpec.getMode(heightMeasureSpec);
    final int widthSize = MeasureSpec.getSize(widthMeasureSpec);
    final int heightSize = MeasureSpec.getSize(heightMeasureSpec);

    final int w;
    final int h;

    if (adapter != null) {
      this.rowCount = adapter.getRowCount();
      this.columnCount = adapter.getColumnCount();

      widths = new int[columnCount + 1];
      for (int i = -1; i < columnCount; i++) {
        widths[i + 1] += adapter.getWidth(i);
      }
      heights = new int[rowCount + 1];
      for (int i = -1; i < rowCount; i++) {
        heights[i + 1] += adapter.getHeight(i);
      }

      if (widthMode == MeasureSpec.AT_MOST) {
        w = Math.min(widthSize, sumArray(widths));
      } else if (widthMode == MeasureSpec.UNSPECIFIED) {
        w = sumArray(widths);
      } else {
        w = widthSize;
        int sumArray = sumArray(widths);
        if (sumArray < widthSize) {
          final float factor = widthSize / (float) sumArray;
          for (int i = 1; i < widths.length; i++) {
            widths[i] = Math.round(widths[i] * factor);
          }
          widths[0] = widthSize - sumArray(widths, 1, widths.length - 1);
        }
      }

      if (heightMode == MeasureSpec.AT_MOST) {
        h = Math.min(heightSize, sumArray(heights));
      } else if (heightMode == MeasureSpec.UNSPECIFIED) {
        h = sumArray(heights);
      } else {
        h = heightSize;
      }
    } else {
      if (heightMode == MeasureSpec.AT_MOST || widthMode == MeasureSpec.UNSPECIFIED) {
        w = 0;
        h = 0;
      } else {
        w = widthSize;
        h = heightSize;
      }
    }

    if (firstRow >= rowCount || getMaxScrollY() - getActualScrollY() < 0) {
      firstRow = 0;
      scrollY = Integer.MAX_VALUE;
    }
    if (firstColumn >= columnCount || getMaxScrollX() - getActualScrollX() < 0) {
      firstColumn = 0;
      scrollX = Integer.MAX_VALUE;
    }

    setMeasuredDimension(w, h);
  }
        public boolean play(Canvas out, Context context) {

          float aspect = out.getHeight() * 1.0f / out.getWidth();
          int width = 1000;
          Bitmap bitmap =
              Bitmap.createBitmap(width, Math.round(width * aspect), Bitmap.Config.RGB_565);
          Canvas c = new Canvas(bitmap);
          bounds = c.getClipBounds();
          windowBounds = out.getClipBounds();

          if (!started) {
            months = new Vector<rectangle>();
            // months.add(new Ball(new
            // Point(bounds.width()/4,10+(2+random.nextInt(10))*(1+random.nextInt(10))),Color.parseColor("#00ff00"),45,bounds));
            List<Rect> rectList = new ArrayList<Rect>();
            rectList.add(
                new Rect(bounds.left, bounds.top, bounds.width() / 4, bounds.height() / 3));
            rectList.add(
                new Rect(
                    bounds.width() / 4, bounds.top, bounds.width() * 2 / 4, bounds.height() / 3));
            rectList.add(
                new Rect(
                    bounds.width() * 2 / 4,
                    bounds.top,
                    bounds.width() * 3 / 4,
                    bounds.height() / 3));
            rectList.add(
                new Rect(bounds.width() * 3 / 4, bounds.top, bounds.right, bounds.height() / 3));

            rectList.add(
                new Rect(
                    bounds.left, bounds.height() / 3, bounds.width() / 4, bounds.height() * 2 / 3));
            rectList.add(
                new Rect(
                    bounds.width() / 4,
                    bounds.height() / 3,
                    bounds.width() * 2 / 4,
                    bounds.height() * 2 / 3));
            rectList.add(
                new Rect(
                    bounds.width() * 2 / 4,
                    bounds.height() / 3,
                    bounds.width() * 3 / 4,
                    bounds.height() * 2 / 3));
            rectList.add(
                new Rect(
                    bounds.width() * 3 / 4,
                    bounds.height() / 3,
                    bounds.right,
                    bounds.height() * 2 / 3));

            rectList.add(
                new Rect(
                    bounds.left,
                    bounds.height() * 2 / 3,
                    bounds.width() / 4,
                    bounds.height() * 3 / 3));
            rectList.add(
                new Rect(
                    bounds.width() / 4,
                    bounds.height() * 2 / 3,
                    bounds.width() * 2 / 4,
                    bounds.height() * 3 / 3));
            rectList.add(
                new Rect(
                    bounds.width() * 2 / 4,
                    bounds.height() * 2 / 3,
                    bounds.width() * 3 / 4,
                    bounds.height() * 3 / 3));
            rectList.add(
                new Rect(
                    bounds.width() * 3 / 4,
                    bounds.height() * 2 / 3,
                    bounds.right,
                    bounds.height() * 3 / 3));

            Collections.shuffle(rectList);
            String boxColour =
                Shared.getOption(context.getString(R.string.Colours) + "/" + boxColourStr, context)
                    .getTextContent();
            // Color boxColour =
            // Color.parseColor(Shared.getOption(context.getString(R.string.Colours) + "/"
            // +boxColourStr  ));

            months.add(
                new rectangle(Color.parseColor(boxColour), rectList.get(0), "January", boxBoundry));
            months.add(
                new rectangle(
                    Color.parseColor(boxColour), rectList.get(1), "February", boxBoundry));
            months.add(
                new rectangle(Color.parseColor(boxColour), rectList.get(2), "March", boxBoundry));
            months.add(
                new rectangle(Color.parseColor(boxColour), rectList.get(3), "April", boxBoundry));

            months.add(
                new rectangle(Color.parseColor(boxColour), rectList.get(4), "May", boxBoundry));
            months.add(
                new rectangle(Color.parseColor(boxColour), rectList.get(5), "June", boxBoundry));
            months.add(
                new rectangle(Color.parseColor(boxColour), rectList.get(6), "July", boxBoundry));
            months.add(
                new rectangle(Color.parseColor(boxColour), rectList.get(7), "August", boxBoundry));

            months.add(
                new rectangle(
                    Color.parseColor(boxColour), rectList.get(8), "September", boxBoundry));
            months.add(
                new rectangle(Color.parseColor(boxColour), rectList.get(9), "October", boxBoundry));
            months.add(
                new rectangle(
                    Color.parseColor(boxColour), rectList.get(10), "November", boxBoundry));
            months.add(
                new rectangle(
                    Color.parseColor(boxColour), rectList.get(11), "December", boxBoundry));

            // Vector v = new Vector();
            //                    Iterator itr = months.iterator();
            //                    while(itr.hasNext())
            //                    {
            //                        itr.next().
            //                    }

            String textColour =
                Shared.getOption(context.getString(R.string.Colours) + "/" + textColourStr, context)
                    .getTextContent();
            for (int i = 0; i < months.size(); i++) {
              months.get(i).setTextSize(textSize);
              months.get(i).setTextColour(textColour);
            }

            //                    setSequenceNumber(months.size());
            //                    sequenceNumber = getSequenceNumber();
            //                    // create a list of random months from the months Vector.
            // SequenceNumber dictates how many random months will be stored in the sequence
            // variable
            //                    for(int i = 0; i< sequenceNumber; i++)
            //                    {
            //                        sequence.add(months.get(i));
            //                    }

            // NB
            // set the SpaceCogViewViewModle's sequence variable
            setDemoSequence(sequence);

            setMonthVector(months);
            started = true;
          }

          if (paint == null) {
            String currentSize =
                Shared.getOptionAtribute(
                    context.getString(R.string.FontSize), getString(R.string.current), context);
            String textColour =
                Shared.getOptionAtribute(
                    context.getString(R.string.Colours), getString(R.string.text), context);
            paint = new Paint();
            paint.setColor(
                Color.parseColor(
                    Shared.getOption(
                            context.getString(R.string.Colours) + "/" + textColour, context)
                        .getTextContent()));
            paint.setTextSize(
                new Integer(
                    Shared.getOption(
                            context.getString(R.string.FontSize) + "/" + currentSize, context)
                        .getTextContent()));
            String font =
                Shared.getOptionAtribute(
                    getString(R.string.Font), getString(R.string.current), getApplicationContext());
            Typeface face =
                Typeface.createFromAsset(
                    getAssets(),
                    Shared.getOption(getString(R.string.Font) + "/" + font, getApplicationContext())
                        .getTextContent());
            paint.setTypeface(face);
          }
          c.drawText("tap the screen", 50, 50, paint);
          c.drawText("to start", 50, 100, paint);
          c.drawText("the test.", 50, 150, paint);
          c.drawText("Pick the Months", 50, 200, paint);
          c.drawText("in reverse order", 50, 250, paint);

          out.drawBitmap(bitmap, c.getClipBounds(), out.getClipBounds(), paint);

          return finished;
        }
    public boolean play(Canvas out, Context context) {
      Paint paint = null;
      float aspect = out.getHeight() * 1.0f / out.getWidth();
      int width = 1000;
      Bitmap bitmap = Bitmap.createBitmap(width, Math.round(width * aspect), Bitmap.Config.RGB_565);
      Canvas c = new Canvas(bitmap);
      bounds = c.getClipBounds();
      windowBounds = out.getClipBounds();

      if (!started) {
        started = true;
        months = getMonthVector();

        paint = new Paint();
        paint.setColor(Color.parseColor("#00ff00"));
        paint.setStrokeWidth(5);
      }

      for (rectangle month : months) {
        // ball.Update();  // the months don't need to be updated
        month.Draw(c);
      }

      out.drawBitmap(bitmap, c.getClipBounds(), out.getClipBounds(), paint);

      //                for(int i = 0; i < userSequenceTest.size(); i++)
      //                {
      //                    if(demoSequence.get(i) != userSequenceTest.get(i))
      //                    {
      //                        sequencesMatch = false;
      //                    }
      //
      //                    if(sequencesMatch == false)
      //                    {
      //                        break;
      //                    }
      //
      //                }

      return false;

      //                // if we've pressed more circles than are in the sequence, then we have
      // failed.
      //                if(monthPressedCount > getDemoSequence().size() || sequencesMatch == false)
      //                {
      //                    // return true when finished
      //                    for(rectangle month: months)
      //                    {
      //                        month.setPressed(false);
      //                    }
      //                    setResult(false);
      //                    return true;
      //                }
      //                // if the sequences match and we have pressed the number of months in the
      // demo sequence
      //                else if(sequencesMatch == true && monthPressedCount == demoSequence.size()){
      //                    // then we have succeded and return true because we have finished
      //
      //                    setResult(true);
      //                    return true;
      //                } else {
      //                    return false;
      //                }

    }
Ejemplo n.º 25
0
 private int ave(int s, int d, float p) {
   return s + Math.round(p * (d - s));
 }
Ejemplo n.º 26
0
 private int floatToByte(float x) {
   int n = Math.round(x);
   return n;
 }
 private int getCurrentPageRound() {
   return Math.round(mFlipDistance / FLIP_DISTANCE_PER_PAGE);
 }