Java Code Examples for android.graphics.Canvas

The following are top voted examples for showing how to use android.graphics.Canvas. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: QMUI_Android   File: QMUIDrawableHelper.java   View source code 7 votes vote down vote up
/**
 * 从一个view创建Bitmap。
 * 注意点:绘制之前要清掉 View 的焦点,因为焦点可能会改变一个 View 的 UI 状态。
 * 来源:https://github.com/tyrantgit/ExplosionField
 *
 * @param view  传入一个 View,会获取这个 View 的内容创建 Bitmap。
 * @param scale 缩放比例,对创建的 Bitmap 进行缩放,数值支持从 0 到 1。
 */
public static Bitmap createBitmapFromView(View view, float scale) {
    if (view instanceof ImageView) {
        Drawable drawable = ((ImageView) view).getDrawable();
        if (drawable != null && drawable instanceof BitmapDrawable) {
            return ((BitmapDrawable) drawable).getBitmap();
        }
    }
    view.clearFocus();
    Bitmap bitmap = createBitmapSafely((int) (view.getWidth() * scale),
            (int) (view.getHeight() * scale), Bitmap.Config.ARGB_8888, 1);
    if (bitmap != null) {
        synchronized (sCanvas) {
            Canvas canvas = sCanvas;
            canvas.setBitmap(bitmap);
            canvas.save();
            canvas.drawColor(Color.WHITE); // 防止 View 上面有些区域空白导致最终 Bitmap 上有些区域变黑
            canvas.scale(scale, scale);
            view.draw(canvas);
            canvas.restore();
            canvas.setBitmap(null);
        }
    }
    return bitmap;
}
 
Example 2
Project: GitHub   File: CrossShapeRenderer.java   View source code 6 votes vote down vote up
@Override
public void renderShape(Canvas c, IScatterDataSet dataSet, ViewPortHandler viewPortHandler,
                        float posX, float posY, Paint renderPaint) {

    final float shapeHalf = dataSet.getScatterShapeSize() / 2f;

    renderPaint.setStyle(Paint.Style.STROKE);
    renderPaint.setStrokeWidth(Utils.convertDpToPixel(1f));

    c.drawLine(
            posX - shapeHalf,
            posY,
            posX + shapeHalf,
            posY,
            renderPaint);
    c.drawLine(
            posX,
            posY - shapeHalf,
            posX,
            posY + shapeHalf,
            renderPaint);

}
 
Example 3
Project: GitHub   File: XAxisRendererHorizontalBarChart.java   View source code 6 votes vote down vote up
@Override
public void renderAxisLine(Canvas c) {

    if (!mXAxis.isDrawAxisLineEnabled() || !mXAxis.isEnabled())
        return;

    mAxisLinePaint.setColor(mXAxis.getAxisLineColor());
    mAxisLinePaint.setStrokeWidth(mXAxis.getAxisLineWidth());

    if (mXAxis.getPosition() == XAxisPosition.TOP
            || mXAxis.getPosition() == XAxisPosition.TOP_INSIDE
            || mXAxis.getPosition() == XAxisPosition.BOTH_SIDED) {
        c.drawLine(mViewPortHandler.contentRight(),
                mViewPortHandler.contentTop(), mViewPortHandler.contentRight(),
                mViewPortHandler.contentBottom(), mAxisLinePaint);
    }

    if (mXAxis.getPosition() == XAxisPosition.BOTTOM
            || mXAxis.getPosition() == XAxisPosition.BOTTOM_INSIDE
            || mXAxis.getPosition() == XAxisPosition.BOTH_SIDED) {
        c.drawLine(mViewPortHandler.contentLeft(),
                mViewPortHandler.contentTop(), mViewPortHandler.contentLeft(),
                mViewPortHandler.contentBottom(), mAxisLinePaint);
    }
}
 
Example 4
Project: UiLib   File: BallGridPulseIndicator.java   View source code 6 votes vote down vote up
@Override
public void draw(Canvas canvas, Paint paint) {
    float circleSpacing=4;
    float radius=(getWidth()-circleSpacing*4)/6;
    float x = getWidth()/ 2-(radius*2+circleSpacing);
    float y = getWidth()/ 2-(radius*2+circleSpacing);

    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            canvas.save();
            float translateX=x+(radius*2)*j+circleSpacing*j;
            float translateY=y+(radius*2)*i+circleSpacing*i;
            canvas.translate(translateX, translateY);
            canvas.scale(scaleFloats[3 * i + j], scaleFloats[3 * i + j]);
            paint.setAlpha(alphas[3 * i + j]);
            canvas.drawCircle(0, 0, radius, paint);
            canvas.restore();
        }
    }
}
 
Example 5
Project: musicplayer   File: UnderlinePageIndicator.java   View source code 6 votes vote down vote up
@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    if (mViewPager == null) {
        return;
    }
    final int count = mViewPager.getAdapter().getCount();
    if (count == 0) {
        return;
    }

    if (mCurrentPage >= count) {
        setCurrentItem(count - 1);
        return;
    }

    final int paddingLeft = getPaddingLeft();
    final float pageWidth = (getWidth() - paddingLeft - getPaddingRight()) / (1f * count);
    final float left = paddingLeft + pageWidth * (mCurrentPage + mPositionOffset);
    final float right = left + pageWidth;
    final float top = getPaddingTop();
    final float bottom = getHeight() - getPaddingBottom();
    canvas.drawRect(left, top, right, bottom, mPaint);
}
 
Example 6
Project: BezierView   File: BezierQuadView.java   View source code 6 votes vote down vote up
@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    mPath.reset();
    //贝塞尔曲线
    mPath.moveTo(mStartXPoint, mStartYPoint);
    mPath.quadTo(mConXPoint, mConYPoint, mEndXPoint, mEndYPoint);
    canvas.drawPath(mPath, mPaint);

    //辅助线
    canvas.drawLine(mStartXPoint, mStartYPoint, mConXPoint, mConYPoint, mLinePaint);
    canvas.drawLine(mConXPoint, mConYPoint, mEndXPoint, mEndYPoint, mLinePaint);

    //文字
    canvas.drawPoint(mStartXPoint, mStartYPoint, mPaint);
    canvas.drawText("起始点", mStartXPoint, mStartYPoint + 30, mTextPaint);
    canvas.drawPoint(mEndXPoint, mEndYPoint, mPaint);
    canvas.drawText("结束点", mEndXPoint, mEndYPoint + 30, mTextPaint);
    canvas.drawPoint(mConXPoint, mConYPoint, mPaint);
    canvas.drawText("控制点", mConXPoint, mConYPoint - 30, mTextPaint);

}
 
Example 7
Project: GitHub   File: BitmapUtils.java   View source code 6 votes vote down vote up
public static Bitmap circleBitmap(Bitmap source) {
    //获取图片的宽度
    int width = source.getWidth();
    //创建一个与source等宽的Bitmap对象
    Bitmap bitmap = Bitmap.createBitmap(width, width, Bitmap.Config.ARGB_8888);
    //创建等大小的画布
    Canvas canvas = new Canvas(bitmap);
    //绘制一个圆圈:将此圆圈理解为下层图片
    Paint paint = new Paint();
    paint.setAntiAlias(true);
    canvas.drawCircle(width / 2, width / 2, width / 2, paint);

    //设置图片相交情况下的处理方式
    //setXfermode:设置当绘制的图像出现相交情况时候的处理方式的,它包含的常用模式有哪几种
    //PorterDuff.Mode.SRC_IN 取两层图像交集部门,只显示上层图像,注意这里是指取相交叉的部分,然后显示上层图像
    //PorterDuff.Mode.DST_IN 取两层图像交集部门,只显示下层图像
    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
    //source:理解为上层图片
    canvas.drawBitmap(source, 0, 0, paint);

    return bitmap;
}
 
Example 8
Project: Phial   File: PhialButton.java   View source code 6 votes vote down vote up
@Override
protected void onDraw(Canvas canvas) {
    int w = getWidth();
    int h = getHeight();

    int cx = w / 2;
    int cy = (int) (h / 2f - getShadowDy());

    int radius = (int) (Math.min(w, h) / 2f - shadowSize);

    canvas.drawCircle(cx, cy, radius, bgPaint);

    if (icon != null) {
        final int targetW = getIconSize(2 * radius, icon.getIntrinsicWidth());
        final int targetH = getIconSize(2 * radius, icon.getIntrinsicHeight());
        icon.setBounds(cx - targetW / 2, cy - targetH / 2, cx + targetW / 2, cy + targetH / 2);
        icon.draw(canvas);
    }
}
 
Example 9
Project: egma-handwriting-numbers   File: DrawView.java   View source code 6 votes vote down vote up
@Override
public void onDraw(Canvas canvas) {
    if (mModel == null) {
        return;
    }
    if (!mSetuped) {
        setup();
    }
    if (mOffscreenBitmap == null) {
        return;
    }

    int startIndex = mDrawnLineSize - 1;
    if (startIndex < 0) {
        startIndex = 0;
    }

    DrawRenderer.renderModel(mOffscreenCanvas, mModel, mPaint, startIndex);
    canvas.drawBitmap(mOffscreenBitmap, mMatrix, mPaint);

    mDrawnLineSize = mModel.getLineSize();
}
 
Example 10
Project: YCSlideView   File: RecycleViewItemLine.java   View source code 6 votes vote down vote up
private void drawHorizontal(Canvas canvas, RecyclerView parent) {
    final int left = parent.getPaddingLeft();
    final int right = parent.getMeasuredWidth() - parent.getPaddingRight();
    final int childSize = parent.getChildCount();
    //childSize-1  最后一个item不显示分割线
    for (int i = 0; i < childSize-1; i++) {
        final View child = parent.getChildAt(i);
        RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) child.getLayoutParams();
        final int top = child.getBottom() + layoutParams.bottomMargin;
        final int bottom = top + mDividerHeight;
        if (mDivider != null) {
            mDivider.setBounds(left, top, right, bottom);
            mDivider.draw(canvas);
        }
        if (mPaint != null) {
            canvas.drawRect(left, top, right, bottom, mPaint);
        }
    }
}
 
Example 11
Project: GitHub   File: YAxisRendererHorizontalBarChart.java   View source code 6 votes vote down vote up
/**
 * draws the y-labels on the specified x-position
 *
 * @param fixedPosition
 * @param positions
 */
@Override
protected void drawYLabels(Canvas c, float fixedPosition, float[] positions, float offset) {

    mAxisLabelPaint.setTypeface(mYAxis.getTypeface());
    mAxisLabelPaint.setTextSize(mYAxis.getTextSize());
    mAxisLabelPaint.setColor(mYAxis.getTextColor());

    final int from = mYAxis.isDrawBottomYLabelEntryEnabled() ? 0 : 1;
    final int to = mYAxis.isDrawTopYLabelEntryEnabled()
            ? mYAxis.mEntryCount
            : (mYAxis.mEntryCount - 1);

    for (int i = from; i < to; i++) {

        String text = mYAxis.getFormattedLabel(i);

        c.drawText(text, positions[i * 2], fixedPosition - offset, mAxisLabelPaint);
    }
}
 
Example 12
Project: RollSquareView   File: Utils.java   View source code 6 votes vote down vote up
/**
 * 确保drawable是能够拿到宽高的drawable
 *
 * @param drawable
 * @return
 */
public static Bitmap drawableToBitmap(Drawable drawable) {
    if (drawable == null
            && drawable.getIntrinsicWidth() > 0
            && drawable.getIntrinsicHeight() > 0) {
        return null;
    }
    Bitmap bitmap = Bitmap
            .createBitmap(
                    drawable.getIntrinsicWidth(),
                    drawable.getIntrinsicHeight(),
                    drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
                            : Bitmap.Config.RGB_565);
    Canvas canvas = new Canvas(bitmap);
    drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
            drawable.getIntrinsicHeight());
    Log.i("Utilities",
            "drawableToBitmap drawable.getIntrinsicWidth()=" + drawable.getIntrinsicWidth()
                    + ",drawable.getIntrinsicHeight()="
                    + drawable.getIntrinsicHeight());
    drawable.draw(canvas);
    return bitmap;
}
 
Example 13
Project: HeadlineNews   File: ImageUtils.java   View source code 6 votes vote down vote up
/**
 * 添加文字水印
 *
 * @param src      源图片
 * @param content  水印文本
 * @param textSize 水印字体大小
 * @param color    水印字体颜色
 * @param x        起始坐标x
 * @param y        起始坐标y
 * @param recycle  是否回收
 * @return 带有文字水印的图片
 */
public static Bitmap addTextWatermark(final Bitmap src,
                                      final String content,
                                      final float textSize,
                                      final int color,
                                      final float x,
                                      final float y,
                                      final boolean recycle) {
    if (isEmptyBitmap(src) || content == null) return null;
    Bitmap ret = src.copy(src.getConfig(), true);
    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    Canvas canvas = new Canvas(ret);
    paint.setColor(color);
    paint.setTextSize(textSize);
    Rect bounds = new Rect();
    paint.getTextBounds(content, 0, content.length(), bounds);
    canvas.drawText(content, x, y + textSize, paint);
    if (recycle && !src.isRecycled()) src.recycle();
    return ret;
}
 
Example 14
Project: SmartRefreshLayout   File: PhoenixHeader.java   View source code 6 votes vote down vote up
private void drawSky(Canvas canvas, int width, int height) {
        Matrix matrix = mMatrix;
        matrix.reset();

        int bWidth = mDrawableSky.width();//mSky.getWidth();
        int bHeight = mDrawableSky.height();//mSky.getHeight();
        float townScale = 1f * width / bWidth;
        float offsetx = 0;
        float offsety = height / 2 - bHeight / 2;

//        matrix.postScale(townScale, townScale);
//        matrix.postTranslate(offsetx, offsety);
//
//        canvas.drawBitmap(mSky, matrix, null);

        final int saveCount = canvas.getSaveCount();
        canvas.save();
        canvas.translate(offsetx, offsety);
        matrix.postScale(townScale, townScale);
        mDrawableSky.draw(canvas);
        canvas.restoreToCount(saveCount);
    }
 
Example 15
Project: diycode   File: ACache.java   View source code 6 votes vote down vote up
private static Bitmap drawable2Bitmap(Drawable drawable) {
    if (drawable == null) {
        return null;
    }
    // 取 drawable 的长宽
    int w = drawable.getIntrinsicWidth();
    int h = drawable.getIntrinsicHeight();
    // 取 drawable 的颜色格式
    Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
            : Bitmap.Config.RGB_565;
    // 建立对应 bitmap
    Bitmap bitmap = Bitmap.createBitmap(w, h, config);
    // 建立对应 bitmap 的画布
    Canvas canvas = new Canvas(bitmap);
    drawable.setBounds(0, 0, w, h);
    // 把 drawable 内容画到画布中
    drawable.draw(canvas);
    return bitmap;
}
 
Example 16
Project: Metronome-Android   File: SeekBar.java   View source code 6 votes vote down vote up
@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    secondaryPaint.setAlpha(255);
    canvas.drawRect(0, 0, canvas.getWidth(), 2, secondaryPaint);

    int currentWidth = (int) (canvas.getWidth() * ((float) progress / maxProgress));
    for (int i = 0; i < maxProgress; i += 10) {
        int width = (int) (canvas.getWidth() * ((float) i / maxProgress));
        secondaryPaint.setAlpha(Math.max(255 - (int) ((float) Math.abs(width - currentWidth) * 1000 / canvas.getWidth()), 0));
        canvas.drawRect(width - 1, 0, width + 1, ConversionUtils.getPixelsFromDp(i % 20 == 0 ? 6 : 4), secondaryPaint);
    }

    canvas.drawRect(0, 0, currentWidth, 2, accentPaint);
    canvas.drawRect(currentWidth - 1, 0, currentWidth + 1, ConversionUtils.getPixelsFromDp(10), accentPaint);
}
 
Example 17
Project: chromium-for-android-56-debug-video   File: FadingEdgeScrollView.java   View source code 6 votes vote down vote up
@Override
protected void dispatchDraw(Canvas canvas) {
    super.dispatchDraw(canvas);
    setVerticalFadingEdgeEnabled(true);
    float topShadowStrength = getTopFadingEdgeStrength();
    float bottomShadowStrength = getBottomFadingEdgeStrength();
    float shadowHeight = getVerticalFadingEdgeLength();
    setVerticalFadingEdgeEnabled(false);

    if (mDrawTopShadow) {
        mFadingShadow.drawShadow(this, canvas, FadingShadow.POSITION_TOP,
                shadowHeight, topShadowStrength);
    }

    if (mDrawBottomShadow) {
        mFadingShadow.drawShadow(this, canvas, FadingShadow.POSITION_BOTTOM,
                shadowHeight, bottomShadowStrength);
    }
}
 
Example 18
Project: Cluttr   File: CropOverlayView.java   View source code 6 votes vote down vote up
/**
 * Draw borders of the crop area.
 */
private void drawBorders(Canvas canvas) {
    if (mBorderPaint != null) {
        float w = mBorderPaint.getStrokeWidth();
        RectF rect = mCropWindowHandler.getRect();
        rect.inset(w / 2, w / 2);

        if (mCropShape == CropImageView.CropShape.RECTANGLE) {
            // Draw rectangle crop window border.
            canvas.drawRect(rect, mBorderPaint);
        } else {
            // Draw circular crop window border
            canvas.drawOval(rect, mBorderPaint);
        }
    }
}
 
Example 19
Project: FlickLauncher   File: LauncherEdgeEffect.java   View source code 6 votes vote down vote up
/**
 * Draw into the provided canvas. Assumes that the canvas has been rotated
 * accordingly and the size has been set. The effect will be drawn the full
 * width of X=0 to X=width, beginning from Y=0 and extending to some factor <
 * 1.f of height.
 *
 * @param canvas Canvas to draw into
 * @return true if drawing should continue beyond this frame to continue the
 *         animation
 */
public boolean draw(Canvas canvas) {
    update();

    final float centerX = mBounds.centerX();
    final float centerY = mBounds.height() - mRadius;

    canvas.scale(1.f, Math.min(mGlowScaleY, 1.f) * mBaseGlowScale, centerX, 0);

    final float displacement = Math.max(0, Math.min(mDisplacement, 1.f)) - 0.5f;
    float translateX = mBounds.width() * displacement / 2;
    mPaint.setAlpha((int) (0xff * mGlowAlpha));
    canvas.drawCircle(centerX + translateX, centerY, mRadius, mPaint);

    boolean oneLastFrame = false;
    if (mState == STATE_RECEDE && mGlowScaleY == 0) {
        mState = STATE_IDLE;
        oneLastFrame = true;
    }

    return mState != STATE_IDLE || oneLastFrame;
}
 
Example 20
Project: PWEditText-SafeKeyboard   File: SafePswText.java   View source code 6 votes vote down vote up
private void drawText(Canvas canvas, String num, int i) {
    int startPosition = getStartPosition();
    Rect mTextBound = new Rect();
    pswTextPaint.getTextBounds(num, 0, num.length(), mTextBound);
    Paint.FontMetrics fontMetrics = pswTextPaint.getFontMetrics();
    float textX = startPosition
            + (float) ((i * (borderWidth + spacingWidth))
                    + (borderWidth / 2 - mTextBound.width() / 2)
                    + (0.5 * spacingWidth));
    float textY = startPosition
            + (getMeasuredHeight() - fontMetrics.bottom + fontMetrics.top)
                    / 2
            - fontMetrics.top;
    if (saveResult != 0 || saveResult < result.size()) {
        canvas.drawText(num, textX, textY, pswTextPaint);
    }
}
 
Example 21
Project: CommonFramework   File: MyItemDecoration.java   View source code 6 votes vote down vote up
@Override
public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
    super.onDraw(c, parent, state);

    int childCount = parent.getChildCount();
    for(int i=0;i<childCount;i++){
        View child=parent.getChildAt(i);

        Paint paint=new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setColor(Color.parseColor("#eeeeee"));
        paint.setStyle(Paint.Style.FILL);
        paint.setStrokeWidth(2);

        int startY=child.getTop()-size;
        int startX=child.getLeft();
        int endY=child.getTop()-size;
        int enx=child.getRight();
        c.drawLine(startX,startY,enx,endY,paint);
    }

}
 
Example 22
Project: Paathshala   File: MainActivity.java   View source code 6 votes vote down vote up
public static Bitmap getCircularBitmapFrom(Bitmap bitmap) {
    if (bitmap == null || bitmap.isRecycled()) {
        return null;
    }
    float radius = bitmap.getWidth() > bitmap.getHeight() ? ((float) bitmap
            .getHeight()) / 2f : ((float) bitmap.getWidth()) / 2f;
    Bitmap canvasBitmap = Bitmap.createBitmap(bitmap.getWidth(),
            bitmap.getHeight(), Bitmap.Config.ARGB_8888);
    BitmapShader shader = new BitmapShader(bitmap, Shader.TileMode.CLAMP,
            Shader.TileMode.CLAMP);
    Paint paint = new Paint();
    paint.setAntiAlias(true);
    paint.setShader(shader);

    Canvas canvas = new Canvas(canvasBitmap);

    canvas.drawCircle(bitmap.getWidth() / 2, bitmap.getHeight() / 2,
            radius, paint);

    return canvasBitmap;
}
 
Example 23
Project: Bailan   File: FlowIndicator.java   View source code 6 votes vote down vote up
/**
 * 重写绘制指示器view
 * @param canvas
 */
@Override
protected void onDraw(Canvas canvas) {
	super.onDraw(canvas);
	float width = (getWidth() - ((radius * 2 * count) + (space * (count - 1)))) / 2.f;

	for (int i = 0; i < count; i++) {
		if (i == seleted) {
			paint.setStyle(Style.FILL);
			canvas.drawBitmap(bmp_selected, width + getPaddingLeft()
					+ radius + i * (space + radius + radius), 0, null);
		} else {
			paint.setStyle(Style.FILL);
			canvas.drawBitmap(bmp_normal, width + getPaddingLeft() + radius
					+ i * (space + radius + radius), 0, null);
		}
	}
}
 
Example 24
Project: betterHotels   File: IconView.java   View source code 6 votes vote down vote up
@Override
protected void onDraw(Canvas canvas){
    Bitmap bitmap = ViewUtils.drawableToBitmap(icon);
    bitmap = Bitmap.createScaledBitmap(bitmap, currentSize, currentSize, false);
    canvas.drawBitmap(bitmap, 0, 0, new Paint());
    if(showText || (showTextWhenLarge && mode == Mode.LARGE)){
        String text = getText();
        RectF rect = new RectF();
        int textHeight = ViewUtils.getTextHeight(text, textPaint);
        int textWidth = ViewUtils.getTextWidth(text, textPaint);
        rect.left = availableWidth - ((textWidth / 2) + textSize / 2);
        rect.right = rect.left + textWidth + (textSize / 2);
        if(3 * textHeight < availableHeight){
            rect.top = 3 * textHeight;
        }else if(2 * textHeight < availableHeight){
            rect.top = 2 * textHeight;
        }else{
            rect.top = 0;
        }
        rect.bottom = rect.top +  textHeight + textSize;
        //Draw the text background
        canvas.drawRect(rect, textBackgroundPaint);
        //Draw the text
        canvas.drawText(text, rect.left + textSize / 2, rect.top + textSize / 2, textPaint);
    }
}
 
Example 25
Project: RLibrary   File: RExItemDecoration.java   View source code 6 votes vote down vote up
@Override
public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
    final RecyclerView.LayoutManager manager = parent.getLayoutManager();
    if (manager instanceof StaggeredGridLayoutManager) {
        return;
    }

    //线性布局
    final LinearLayoutManager layoutManager = (LinearLayoutManager) manager;
    final int firstItem = layoutManager.findFirstVisibleItemPosition();
    for (int i = 0; i < layoutManager.getChildCount(); i++) {
        final int viewAdapterPosition = firstItem + i;
        final View view = layoutManager.findViewByPosition(viewAdapterPosition);
        if (view != null) {
            mItemDecorationCallback.draw(c, mTextPaint, view,
                    mItemDecorationCallback.getItemOffsets(layoutManager, viewAdapterPosition),
                    layoutManager.getItemCount(), viewAdapterPosition);
        }
    }
}
 
Example 26
Project: GravityBox   File: Utils.java   View source code 6 votes vote down vote up
public static Bitmap drawableToBitmap(Drawable drawable) {
    if (drawable == null) return null;

    if (drawable instanceof BitmapDrawable) {
        return ((BitmapDrawable) drawable).getBitmap();
    }

    int width = drawable.getIntrinsicWidth();
    width = width > 0 ? width : 1;
    int height = drawable.getIntrinsicHeight();
    height = height > 0 ? height : 1;

    Bitmap bitmap = Bitmap.createBitmap(width, height, Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
    drawable.draw(canvas);

    return bitmap;
}
 
Example 27
Project: androidthings-imageclassifier   File: Helper.java   View source code 6 votes vote down vote up
public static void cropAndRescaleBitmap(final Bitmap src, final Bitmap dst, int sensorOrientation) {
    Assert.assertEquals(dst.getWidth(), dst.getHeight());
    final float minDim = Math.min(src.getWidth(), src.getHeight());

    final Matrix matrix = new Matrix();

    // We only want the center square out of the original rectangle.
    final float translateX = -Math.max(0, (src.getWidth() - minDim) / 2);
    final float translateY = -Math.max(0, (src.getHeight() - minDim) / 2);
    matrix.preTranslate(translateX, translateY);

    final float scaleFactor = dst.getHeight() / minDim;
    matrix.postScale(scaleFactor, scaleFactor);

    // Rotate around the center if necessary.
    if (sensorOrientation != 0) {
        matrix.postTranslate(-dst.getWidth() / 2.0f, -dst.getHeight() / 2.0f);
        matrix.postRotate(sensorOrientation);
        matrix.postTranslate(dst.getWidth() / 2.0f, dst.getHeight() / 2.0f);
    }

    final Canvas canvas = new Canvas(dst);
    canvas.drawBitmap(src, matrix, null);
}
 
Example 28
Project: RLibrary   File: ImageUtils.java   View source code 5 votes vote down vote up
/**
 * 添加文字水印
 *
 * @param src      源图片
 * @param content  水印文本
 * @param textSize 水印字体大小
 * @param color    水印字体颜色
 * @param x        起始坐标x
 * @param y        起始坐标y
 * @param recycle  是否回收
 * @return 带有文字水印的图片
 */
public static Bitmap addTextWatermark(Bitmap src, String content, float textSize, int color, float x,
                                      float y, boolean recycle) {
    if (isEmptyBitmap(src) || content == null) return null;
    Bitmap ret = src.copy(src.getConfig(), true);
    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    Canvas canvas = new Canvas(ret);
    paint.setColor(color);
    paint.setTextSize(textSize);
    Rect bounds = new Rect();
    paint.getTextBounds(content, 0, content.length(), bounds);
    canvas.drawText(content, x, y + textSize, paint);
    if (recycle && !src.isRecycled()) src.recycle();
    return ret;
}
 
Example 29
Project: QMUI_Android   File: QMUIQQFaceView.java   View source code 5 votes vote down vote up
private void handleQQFaceAfterMiddleEllipsize(Canvas canvas, int res, Drawable specialDrawable, int widthStart,
                                              int widthEnd, int ellipsizeLine, boolean isFirst, boolean isLast) {
    int size = res != 0 ? mQQFaceSize : specialDrawable.getIntrinsicWidth() + (isFirst || isLast ? mSpecialDrawablePadding : mSpecialDrawablePadding * 2);
    if (mMiddleEllipsizeWidthRecord == -1) {
        onRealDrawQQFace(canvas, res, specialDrawable, ellipsizeLine - mLastNeedStopLineRecord, widthStart, widthEnd, isFirst, isLast);
        return;
    }

    int endLines = mNeedDrawLine - ellipsizeLine;
    int borrowWidth = (widthEnd - mMiddleEllipsizeWidthRecord) - mCurrentCalWidth;
    int needStopLine = borrowWidth > 0 ? mLines - endLines - 1 : mLines - endLines;
    int needStopWidth = (borrowWidth > 0 ? widthEnd - borrowWidth :
            mMiddleEllipsizeWidthRecord - (widthEnd - mCurrentCalWidth)) +
            QMUIDisplayHelper.dp2px(getContext(), 5);

    if (mCurrentDrawLine < needStopLine) {
        if (size + mCurrentDrawUsedWidth > widthEnd) {
            toNewDrawLine(widthStart);
            onDrawQQFace(canvas, res, specialDrawable, widthStart, widthEnd, isFirst, isLast);
        } else {
            mCurrentDrawUsedWidth += size;
        }
    } else if (mCurrentDrawLine == needStopLine) {
        if (size + mCurrentDrawUsedWidth < needStopWidth) {
            mCurrentDrawUsedWidth += size;
        } else {
            mCurrentDrawUsedWidth = mMiddleEllipsizeWidthRecord;
            mMiddleEllipsizeWidthRecord = -1;
            mLastNeedStopLineRecord = needStopLine;
        }
    } else {
        onRealDrawQQFace(canvas, res, specialDrawable, ellipsizeLine - needStopLine, widthStart, widthEnd, isFirst, isLast);
    }
}
 
Example 30
Project: miaosou   File: DividerItemDecoration.java   View source code 5 votes vote down vote up
@Override
public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
    final int left = parent.getPaddingLeft();
    final int right = parent.getWidth() - parent.getPaddingRight();
    final int childCount = parent.getChildCount();
    for(int i = 0;i < childCount;i ++){
        final View child = parent.getChildAt(i);
        RecyclerView view = new RecyclerView(parent.getContext());
        final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
        final int top = child.getBottom() + params.bottomMargin;
        final int bottom = top + mDivider.getIntrinsicHeight();
        mDivider.setBounds(left,top,right,bottom);
        mDivider.draw(c);
    }
}
 
Example 31
Project: tvConnect_android   File: CaptureActivity.java   View source code 5 votes vote down vote up
private static void drawLine(Canvas canvas, Paint paint, ResultPoint a,
                             ResultPoint b, float scaleFactor) {
    if (a != null && b != null) {
        canvas.drawLine(scaleFactor * a.getX(), scaleFactor * a.getY(),
                scaleFactor * b.getX(), scaleFactor * b.getY(), paint);
    }
}
 
Example 32
Project: SwipeToRefresh   File: ProgressImage.java   View source code 5 votes vote down vote up
@Override
public void draw(Canvas canvas, Paint paint) {
    final int viewWidth = ProgressImage.this.getWidth();
    final int viewHeight = ProgressImage.this.getHeight();
    canvas.drawCircle(viewWidth / 2, viewHeight / 2, (mCircleDiameter / 2 + mShadowRadius),
            mShadowPaint);
    canvas.drawCircle(viewWidth / 2, viewHeight / 2, (mCircleDiameter / 2), paint);
}
 
Example 33
Project: LoadingViews   File: LoadingView.java   View source code 5 votes vote down vote up
@Override
protected void onDraw(Canvas canvas) {
    if (!isInEditMode())
        mLoadingView.onDraw(canvas);
    else
        EditModeDrawer.drawEditMode(type,canvas,getWidth(),getHeight(),contentPadding, Color.GRAY);
}
 
Example 34
Project: QRCodeScanner   File: DefaultScanCursorView.java   View source code 5 votes vote down vote up
protected void drawCorners(Canvas canvas, Rect rect) {

        canvas.drawBitmap(mCorner1, rect.left, rect.top, null);
        canvas.drawBitmap(mCorner2, rect.right - mCorner2.getWidth(), rect.top, null);
        canvas.drawBitmap(mCorner3, rect.left, rect.bottom - mCorner3.getHeight(), null);
        canvas.drawBitmap(mCorner4, rect.right - mCorner4.getWidth(),
                rect.bottom - mCorner4.getHeight(), null);

    }
 
Example 35
Project: mupdf-android-viewer-nui   File: WheelView.java   View source code 5 votes vote down vote up
/**
 * Draws rect for current value
 * @param canvas the canvas for drawing
 */
private void drawCenterRect(Canvas canvas) {
    int center = getHeight() / 2;
    int offset = (int) (getItemHeight() / 2 * 1.2);
    centerDrawable.setBounds(0, center - offset, getWidth(), center + offset);
    centerDrawable.draw(canvas);
}
 
Example 36
Project: Android-Music-Player   File: playBtn.java   View source code 5 votes vote down vote up
@Override
protected void onDraw(Canvas canvas) {
    PlayBtn.draw(canvas);
    super.postDraw(canvas);
    if(isPlaying){
        playing.draw(canvas);
    } else {
        stoped.draw(canvas);
    }
    super.afterDraw(canvas,PlayBtn.S0);
}
 
Example 37
Project: CodeCompilerApp   File: MainActivity.java   View source code 5 votes vote down vote up
@Override
public void onDraw(@NonNull final Canvas canvas) {

    if (lineCount != getLineCount() || startingLine != pageSystem.getStartingLine()) {
        startingLine = pageSystem.getStartingLine();
        lineCount = getLineCount();
        lineUtils.updateHasNewLineArray(pageSystem
                .getStartingLine(), lineCount, getLayout(), getText().toString());

        isGoodLineArray = lineUtils.getGoodLines();
        realLines = lineUtils.getRealLines();

    }

    if (PreferenceHelper.getLineNumbers(getContext())) {
        wrapContent = PreferenceHelper.getWrapContent(getContext());

        for (int i = 0; i < lineCount; i++) {
            // if last line we count it anyway
            if (!wrapContent
                    || isGoodLineArray[i]) {
                realLine = realLines[i];

                canvas.drawText(String.valueOf(realLine),
                        numbersWidth, // they are all center aligned
                        paddingTop + lineHeight * (i + 1),
                        mPaintNumbers);
            }
        }
    }

    super.onDraw(canvas);
}
 
Example 38
Project: simple-keyboard   File: DrawingPreviewPlacerView.java   View source code 5 votes vote down vote up
@Override
public void onDraw(final Canvas canvas) {
    super.onDraw(canvas);
    final int originX = CoordinateUtils.x(mKeyboardViewOrigin);
    final int originY = CoordinateUtils.y(mKeyboardViewOrigin);
    canvas.translate(originX, originY);
    canvas.translate(-originX, -originY);
}
 
Example 39
Project: GitHub   File: PathsDrawable.java   View source code 5 votes vote down vote up
@Override
public void draw(@NonNull Canvas canvas) {
    Rect bounds = getBounds();
    int width = bounds.width();
    int height = bounds.height();
    if (mPaint.getAlpha() == 0xFF) {
        canvas.save();
        canvas.translate(bounds.left-mStartX, bounds.top-mStartY);
        if (mPaths != null) {
            for (int i = 0; i < mPaths.size(); i++) {
                if (mColors != null && i < mColors.size()) {
                    mPaint.setColor(mColors.get(i));
                }
                canvas.drawPath(mPaths.get(i), mPaint);
            }
            mPaint.setAlpha(0xFF);
        }
        canvas.restore();
    } else {
        createCachedBitmapIfNeeded(width, height);
        if (!canReuseCache()) {
            updateCachedBitmap(width, height);
            updateCacheStates();
        }
        canvas.drawBitmap(mCachedBitmap, bounds.left, bounds.top, mPaint);
    }
}
 
Example 40
Project: FriendBook   File: PageView.java   View source code 5 votes vote down vote up
@Override
protected void onDraw(Canvas canvas) {

    //绘制背景
    canvas.drawColor(mBgColor);

    //绘制动画
    mPageAnim.draw(canvas);
}