Java Code Examples for android.graphics.Canvas#setBitmap()

The following examples show how to use android.graphics.Canvas#setBitmap() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PreloadIconDrawable.java    From LaunchEnr with GNU General Public License v3.0 6 votes vote down vote up
private Bitmap getShadowBitmap(int width, int height, float shadowRadius) {
    int key = (width << 16) | height;
    WeakReference<Bitmap> shadowRef = sShadowCache.get(key);
    Bitmap shadow = shadowRef != null ? shadowRef.get() : null;
    if (shadow != null) {
        return shadow;
    }
    shadow = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    Canvas c = new Canvas(shadow);
    mProgressPaint.setShadowLayer(shadowRadius, 0, 0, COLOR_SHADOW);
    mProgressPaint.setColor(COLOR_TRACK);
    mProgressPaint.setAlpha(MAX_PAINT_ALPHA);
    c.drawPath(mScaledTrackPath, mProgressPaint);
    mProgressPaint.clearShadowLayer();
    c.setBitmap(null);

    sShadowCache.put(key, new WeakReference<>(shadow));
    return shadow;
}
 
Example 2
Source File: RxHeartView.java    From RxTools-master with Apache License 2.0 6 votes vote down vote up
public Bitmap createHeart(int color) {
    if (sHeart == null) {
        sHeart = BitmapFactory.decodeResource(getResources(), mHeartResId);
    }
    if (sHeartBorder == null) {
        sHeartBorder = BitmapFactory.decodeResource(getResources(), mHeartBorderResId);
    }
    Bitmap heart = sHeart;
    Bitmap heartBorder = sHeartBorder;
    Bitmap bm = createBitmapSafely(heartBorder.getWidth(), heartBorder.getHeight());
    if (bm == null) {
        return null;
    }
    Canvas canvas = sCanvas;
    canvas.setBitmap(bm);
    Paint p = sPaint;
    canvas.drawBitmap(heartBorder, 0, 0, p);
    p.setColorFilter(new PorterDuffColorFilter(color, PorterDuff.Mode.SRC_ATOP));
    float dx = (heartBorder.getWidth() - heart.getWidth()) / 2f;
    float dy = (heartBorder.getHeight() - heart.getHeight()) / 2f;
    canvas.drawBitmap(heart, dx, dy, p);
    p.setColorFilter(null);
    canvas.setBitmap(null);
    return bm;
}
 
Example 3
Source File: HeartView.java    From KSYMediaPlayer_Android with Apache License 2.0 6 votes vote down vote up
public Bitmap createHeart(int color) {
    if (sHeart == null) {
        sHeart = BitmapFactory.decodeResource(getResources(), mHeartResId);
    }
    if (sHeartBorder == null) {
        sHeartBorder = BitmapFactory.decodeResource(getResources(), mHeartBorderResId);
    }
    Bitmap heart = sHeart;
    Bitmap heartBorder = sHeartBorder;
    Bitmap bm = createBitmapSafely(heartBorder.getWidth(), heartBorder.getHeight());
    if (bm == null) {
        return null;
    }
    Canvas canvas = sCanvas;
    canvas.setBitmap(bm);
    Paint p = sPaint;
    canvas.drawBitmap(heartBorder, 0, 0, p);
    p.setColorFilter(new PorterDuffColorFilter(color, PorterDuff.Mode.SRC_ATOP));
    float dx = (heartBorder.getWidth() - heart.getWidth()) / 2f;
    float dy = (heartBorder.getHeight() - heart.getHeight()) / 2f;
    canvas.drawBitmap(heart, dx, dy, p);
    p.setColorFilter(null);
    canvas.setBitmap(null);
    return bm;
}
 
Example 4
Source File: ViewUtils.java    From Readhub with Apache License 2.0 6 votes vote down vote up
/**
 * 从一个view创建Bitmap:
 * 注意点:绘制之前要清掉 View 的焦点,因为焦点可能会改变一个 View 的 UI 状态
 * 来源:https://github.com/tyrantgit/ExplosionField
 *
 * @param view
 * @return
 */
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 5
Source File: PLUtils.java    From panoramagl with Apache License 2.0 6 votes vote down vote up
public static Bitmap convertBitmap(Bitmap bitmap, Config config) {
    if (bitmap != null && bitmap.getConfig() != config) {
        try {
            Bitmap newBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), config);
            Canvas canvas = new Canvas();
            canvas.setBitmap(newBitmap);
            Paint paint = new Paint();
            paint.setFilterBitmap(true);
            canvas.drawBitmap(bitmap, 0, 0, paint);
            return newBitmap;
        } catch (Throwable e) {
            PLLog.error("PLUtils::convertBitmap", e);
        }
    }
    return bitmap;
}
 
Example 6
Source File: GestureDrawline.java    From iMoney with Apache License 2.0 6 votes vote down vote up
public GestureDrawline(Context context, List<GesturePoint> list, boolean isVerify,
                       String passWord, GestureCallBack callBack) {
    super(context);
    screenDispaly = AppUtil.getScreenDispaly(context);
    paint = new Paint(Paint.DITHER_FLAG);// 创建一个画笔
    bitmap = Bitmap.createBitmap(screenDispaly[0], screenDispaly[0], Bitmap.Config.ARGB_8888); // 设置位图的宽高
    canvas = new Canvas();
    canvas.setBitmap(bitmap);
    paint.setStyle(Paint.Style.STROKE);// 设置非填充
    paint.setStrokeWidth(10);// 笔宽5像素
    paint.setColor(Color.rgb(245, 142, 33));// 设置默认连线颜色
    paint.setAntiAlias(true);// 不显示锯齿

    this.list = list;
    this.lineList = new ArrayList<Pair<GesturePoint, GesturePoint>>();

    initAutoCheckPointMap();
    this.callBack = callBack;

    // 初始化密码缓存
    this.isVerify = isVerify;
    this.passWordSb = new StringBuilder();
    this.passWord = passWord;
}
 
Example 7
Source File: BubbleTextView.java    From TurboLauncher with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a new bitmap to be used as the object outline, e.g. to visualize the drop location.
 * Responsibility for the bitmap is transferred to the caller.
 */
private Bitmap createGlowingOutline(Canvas canvas, int outlineColor, int glowColor) {
    final int padding = mOutlineHelper.mMaxOuterBlurRadius;
    final Bitmap b = Bitmap.createBitmap(
            getWidth() + padding, getHeight() + padding, Bitmap.Config.ARGB_8888);

    canvas.setBitmap(b);
    drawWithPadding(canvas, padding);
    mOutlineHelper.applyExtraThickExpensiveOutlineWithBlur(b, canvas, glowColor, outlineColor);
    canvas.setBitmap(null);

    return b;
}
 
Example 8
Source File: ShortcutDragPreviewProvider.java    From LaunchEnr with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Bitmap createDragOutline(Canvas canvas) {
    Bitmap b = drawScaledPreview(canvas, Bitmap.Config.ALPHA_8);

    HolographicOutlineHelper.getInstance(mView.getContext())
            .applyExpensiveOutlineWithBlur(b, canvas);
    canvas.setBitmap(null);
    return b;
}
 
Example 9
Source File: BookmarkUtils.java    From android-chromium with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Creates an icon to be associated with this bookmark. If available, the touch icon
 * will be used, else we draw our own.
 * @param context Context used to create the intent.
 * @param favicon Bookmark favicon bitmap.
 * @param rValue Red component of the dominant favicon color.
 * @param gValue Green component of the dominant favicon color.
 * @param bValue Blue component of the dominant favicon color.
 * @return Bitmap Either the touch-icon or the newly created favicon.
 */
private static Bitmap createIcon(Context context, Bitmap favicon, int rValue,
        int gValue, int bValue) {
    Bitmap bitmap = null;
    ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    final int iconSize = am.getLauncherLargeIconSize();
    final int iconDensity = am.getLauncherLargeIconDensity();
    try {
        bitmap = Bitmap.createBitmap(iconSize, iconSize, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        if (favicon == null) {
            favicon = getBitmapFromResourceId(context, R.drawable.globe_favicon, iconDensity);
            rValue = gValue = bValue = DEFAULT_RGB_VALUE;
        }
        final int smallestSide = iconSize;
        if (favicon.getWidth() >= smallestSide / 2 && favicon.getHeight() >= smallestSide / 2) {
            drawTouchIconToCanvas(context, favicon, canvas);
        } else {
            drawWidgetBackgroundToCanvas(context, canvas, iconDensity,
                    Color.rgb(rValue, gValue, bValue));
            drawFaviconToCanvas(context, favicon, canvas);
        }
        canvas.setBitmap(null);
    } catch (OutOfMemoryError e) {
        Log.w(TAG, "OutOfMemoryError while trying to draw bitmap on canvas.");
    }
    return bitmap;
}
 
Example 10
Source File: ScreenShotUtil.java    From browser with GNU General Public License v2.0 5 votes vote down vote up
public static Bitmap capture(View view, float width, float height, boolean scroll, Bitmap.Config config) {
    if (!view.isDrawingCacheEnabled()) {
        view.setDrawingCacheEnabled(true);
    }
    if(width==0){
        width= MainApp.getInstance().getScreenWidth();
    }
    if(height==0){
        height= MainApp.getInstance().getScreenHeight();
    }

    Bitmap bitmap = Bitmap.createBitmap((int) width, (int) height, config);
    bitmap.eraseColor(Color.WHITE);
    Canvas canvas = new Canvas(bitmap);
    int left = view.getLeft();
    int top = view.getTop();
    if (scroll) {
        left = view.getScrollX();
        top = view.getScrollY();
    }
    int status = canvas.save();
    canvas.translate(-left, -top);
    float scale = width / view.getWidth();
    canvas.scale(scale, scale, left, top);
    view.draw(canvas);
    canvas.restoreToCount(status);
    Paint alphaPaint = new Paint();
    alphaPaint.setColor(Color.TRANSPARENT);
    canvas.drawRect(0f, 0f, 1f, height, alphaPaint);
    canvas.drawRect(width - 1f, 0f, width, height, alphaPaint);
    canvas.drawRect(0f, 0f, width, 1f, alphaPaint);
    canvas.drawRect(0f, height - 1f, width, height, alphaPaint);
    canvas.setBitmap(null);
    return bitmap;
}
 
Example 11
Source File: ShadowGenerator.java    From LaunchEnr with GNU General Public License v3.0 5 votes vote down vote up
public static Bitmap createPillWithShadow(int rectColor, int width, int height) {

        float shadowRadius = height * 1f / 32;
        float shadowYOffset = height * 1f / 16;

        int radius = height / 2;

        Canvas canvas = new Canvas();
        Paint blurPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
        blurPaint.setMaskFilter(new BlurMaskFilter(shadowRadius, Blur.NORMAL));

        int centerX = Math.round(width / 2 + shadowRadius);
        int centerY = Math.round(radius + shadowRadius + shadowYOffset);
        int center = Math.max(centerX, centerY);
        int size = center * 2;
        Bitmap result = Bitmap.createBitmap(size, size, Config.ARGB_8888);
        canvas.setBitmap(result);

        int left = center - width / 2;
        int top = center - height / 2;
        int right = center + width / 2;
        int bottom = center + height / 2;

        // Draw ambient shadow, center aligned within size
        blurPaint.setAlpha(AMBIENT_SHADOW_ALPHA);
        canvas.drawRoundRect(left, top, right, bottom, radius, radius, blurPaint);

        // Draw key shadow, bottom aligned within size
        blurPaint.setAlpha(KEY_SHADOW_ALPHA);
        canvas.drawRoundRect(left, top + shadowYOffset, right, bottom + shadowYOffset,
                radius, radius, blurPaint);

        // Draw the circle
        Paint drawPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
        drawPaint.setColor(rectColor);
        canvas.drawRoundRect(left, top, right, bottom, radius, radius, drawPaint);

        return result;
    }
 
Example 12
Source File: IconCache.java    From FastAccess with GNU General Public License v3.0 5 votes vote down vote up
private Bitmap makeDefaultIcon() {
    Drawable d = getFullResDefaultActivityIcon();
    Bitmap b = Bitmap.createBitmap(Math.max(d.getIntrinsicWidth(), 1),
            Math.max(d.getIntrinsicHeight(), 1),
            Bitmap.Config.ARGB_8888);
    Canvas c = new Canvas(b);
    d.setBounds(0, 0, b.getWidth(), b.getHeight());
    d.draw(c);
    c.setBitmap(null);
    return b;
}
 
Example 13
Source File: PCanvas.java    From PHONK with GNU General Public License v3.0 5 votes vote down vote up
public void prepare(int w, int h) {
    if (mTransparentBmp != null) {
        mTransparentBmp.recycle();
    }
    // mCanvasBuffer = new Canvas();

    mCanvasBuffer = new Canvas();
    mTransparentBmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
    mCanvasBuffer.setBitmap(mTransparentBmp);

    // mPCanvas.setCanvas(canvas);

}
 
Example 14
Source File: Training.java    From marvel with MIT License 4 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_training);

    /*Toolbar toolbar = (Toolbar) findViewById(R.id.app_bar);
    setSupportActionBar(toolbar);

    if(getSupportActionBar() != null) {
        getSupportActionBar().setTitle("Training");
    }*/

    text = getIntent().getStringExtra("name");
    Iv = (ImageView) findViewById(R.id.imagePreview);

    capture = (ToggleButton) findViewById(R.id.capture);
    capture.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            captureOnClick();
        }
    });

    mOpenCvCameraView = (Tutorial3View) findViewById(R.id.tutorial3_activity_java_surface_view);
    mOpenCvCameraView.setCvCameraViewListener(this);

    //mPath=getFilesDir()+"/facerecogOCV/";
    mPath = Environment.getExternalStorageDirectory()+"/facerecogOCV/";

    Log.e("Path", mPath);

    labelsFile= new Labels(mPath);

    mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.obj=="IMG")
            {
                Canvas canvas = new Canvas();
                canvas.setBitmap(mBitmap);
                Iv.setImageBitmap(mBitmap);
                if (countImages>=MAXIMG-1)
                {
                    capture.setChecked(false);
                    captureOnClick();
                }
            }
        }
    };

    boolean success=(new File(mPath)).mkdirs();

    if (!success)
        Log.e("Error","Error creating directory");

}
 
Example 15
Source File: WidgetPreviewLoader.java    From Trebuchet with GNU General Public License v3.0 4 votes vote down vote up
private Bitmap generateShortcutPreview(
        Launcher launcher, ResolveInfo info, int maxWidth, int maxHeight, Bitmap preview) {
    final Canvas c = new Canvas();
    if (preview == null) {
        preview = Bitmap.createBitmap(maxWidth, maxHeight, Config.ARGB_8888);
        c.setBitmap(preview);
    } else if (preview.getWidth() != maxWidth || preview.getHeight() != maxHeight) {
        throw new RuntimeException("Improperly sized bitmap passed as argument");
    } else {
        // Reusing bitmap. Clear it.
        c.setBitmap(preview);
        c.drawColor(0, PorterDuff.Mode.CLEAR);
    }

    Drawable icon = mutateOnMainThread(mIconCache.getFullResIcon(info.activityInfo));
    icon.setFilterBitmap(true);

    // Draw a desaturated/scaled version of the icon in the background as a watermark
    ColorMatrix colorMatrix = new ColorMatrix();
    colorMatrix.setSaturation(0);
    icon.setColorFilter(new ColorMatrixColorFilter(colorMatrix));
    icon.setAlpha((int) (255 * 0.06f));

    Resources res = mContext.getResources();
    int paddingTop = res.getDimensionPixelOffset(R.dimen.shortcut_preview_padding_top);
    int paddingLeft = res.getDimensionPixelOffset(R.dimen.shortcut_preview_padding_left);
    int paddingRight = res.getDimensionPixelOffset(R.dimen.shortcut_preview_padding_right);
    int scaledIconWidth = (maxWidth - paddingLeft - paddingRight);
    icon.setBounds(paddingLeft, paddingTop,
            paddingLeft + scaledIconWidth, paddingTop + scaledIconWidth);
    icon.draw(c);

    // Draw the final icon at top left corner.
    // TODO: use top right for RTL
    int appIconSize = launcher.getDeviceProfile().iconSizePx;

    icon.setAlpha(255);
    icon.setColorFilter(null);
    icon.setBounds(0, 0, appIconSize, appIconSize);
    icon.draw(c);

    c.setBitmap(null);
    return preview;
}
 
Example 16
Source File: HolographicOutlineHelper.java    From LaunchEnr with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Applies a more expensive and accurate outline to whatever is currently drawn in a specified
 * bitmap.
 */
public void applyExpensiveOutlineWithBlur(Bitmap srcDst, Canvas srcDstCanvas) {

    // We start by removing most of the alpha channel so as to ignore shadows, and
    // other types of partial transparency when defining the shape of the object
    byte[] pixels = new byte[srcDst.getWidth() * srcDst.getHeight()];
    ByteBuffer buffer = ByteBuffer.wrap(pixels);
    buffer.rewind();
    srcDst.copyPixelsToBuffer(buffer);

    for (int i = 0; i < pixels.length; i++) {
        if ((pixels[i] & 0xFF) < 188) {
            pixels[i] = 0;
        }
    }

    buffer.rewind();
    srcDst.copyPixelsFromBuffer(buffer);

    // calculate the outer blur first
    mBlurPaint.setMaskFilter(mMediumOuterBlurMaskFilter);
    int[] outerBlurOffset = new int[2];
    Bitmap thickOuterBlur = srcDst.extractAlpha(mBlurPaint, outerBlurOffset);

    mBlurPaint.setMaskFilter(mThinOuterBlurMaskFilter);
    int[] brightOutlineOffset = new int[2];
    Bitmap brightOutline = srcDst.extractAlpha(mBlurPaint, brightOutlineOffset);

    // calculate the inner blur
    srcDstCanvas.setBitmap(srcDst);
    srcDstCanvas.drawColor(0xFF000000, PorterDuff.Mode.SRC_OUT);
    mBlurPaint.setMaskFilter(mMediumInnerBlurMaskFilter);
    int[] thickInnerBlurOffset = new int[2];
    Bitmap thickInnerBlur = srcDst.extractAlpha(mBlurPaint, thickInnerBlurOffset);

    // mask out the inner blur
    srcDstCanvas.setBitmap(thickInnerBlur);
    srcDstCanvas.drawBitmap(srcDst, -thickInnerBlurOffset[0],
            -thickInnerBlurOffset[1], mErasePaint);
    srcDstCanvas.drawRect(0, 0, -thickInnerBlurOffset[0], thickInnerBlur.getHeight(),
            mErasePaint);
    srcDstCanvas.drawRect(0, 0, thickInnerBlur.getWidth(), -thickInnerBlurOffset[1],
            mErasePaint);

    // draw the inner and outer blur
    srcDstCanvas.setBitmap(srcDst);
    srcDstCanvas.drawColor(0, PorterDuff.Mode.CLEAR);
    srcDstCanvas.drawBitmap(thickInnerBlur, thickInnerBlurOffset[0], thickInnerBlurOffset[1],
            mDrawPaint);
    srcDstCanvas.drawBitmap(thickOuterBlur, outerBlurOffset[0], outerBlurOffset[1],
            mDrawPaint);

    // draw the bright outline
    srcDstCanvas.drawBitmap(brightOutline, brightOutlineOffset[0], brightOutlineOffset[1],
            mDrawPaint);

    // cleanup
    srcDstCanvas.setBitmap(null);
    brightOutline.recycle();
    thickOuterBlur.recycle();
    thickInnerBlur.recycle();
}
 
Example 17
Source File: XulWorker.java    From starcor.xul with GNU Lesser General Public License v3.0 4 votes vote down vote up
private static Bitmap toRoundCornerShadowBitmap(Canvas canvas, Paint paintSolid, Paint paintSrcIn, Paint paintDstOut, Paint paintShadow, Bitmap srcBitmap, float[] roundRadius, float shadowSize, int shadowColor) {
	int borderSize = XulUtils.roundToInt(shadowSize) * 2;
	Bitmap output;
	if (false) {
		output = BitmapTools.createBitmapFromRecycledBitmaps(srcBitmap.getWidth(), srcBitmap.getHeight(), XulManager.DEF_PIXEL_FMT);
	} else {
		output = BitmapTools.createBitmap(srcBitmap.getWidth(), srcBitmap.getHeight(), XulManager.DEF_PIXEL_FMT);
	}
	canvas.setBitmap(output);
	Rect rectSrc = new Rect(0, 0, srcBitmap.getWidth(), srcBitmap.getHeight());
	Rect rectDst = new Rect(rectSrc);
	XulUtils.offsetRect(rectDst, borderSize / 2, borderSize / 2);
	RectF rectF = new RectF(rectDst);
	if (roundRadius.length == 2) {
		float rY = roundRadius[1];
		float rX = roundRadius[0];
		canvas.drawRoundRect(rectF, rX, rY, paintSolid);
		canvas.drawBitmap(srcBitmap, rectSrc, rectDst, paintSrcIn);

		XulUtils.saveCanvasLayer(canvas, 0, 0, output.getWidth(), output.getHeight(), paintSolid, Canvas.HAS_ALPHA_LAYER_SAVE_FLAG);
		paintShadow.setShadowLayer(shadowSize, 0, 0, shadowColor);
		canvas.drawRoundRect(rectF, rX, rY, paintShadow);
		canvas.drawRoundRect(rectF, rX, rY, paintDstOut);
		XulUtils.restoreCanvas(canvas);
	} else {
		RoundRectShape roundRectShape = new RoundRectShape(roundRadius, null, null);
		roundRectShape.resize(rectF.width(), rectF.height());

		XulUtils.saveCanvas(canvas);
		canvas.translate(rectF.left, rectF.top);
		roundRectShape.draw(canvas, paintSolid);
		canvas.translate(-rectF.left, -rectF.top);

		canvas.drawBitmap(srcBitmap, rectSrc, rectDst, paintSrcIn);
		XulUtils.saveCanvasLayer(canvas, 0, 0, output.getWidth(), output.getHeight(), paintSolid, Canvas.HAS_ALPHA_LAYER_SAVE_FLAG);
		paintShadow.setShadowLayer(shadowSize, 0, 0, shadowColor);

		canvas.translate(rectF.left, rectF.top);
		roundRectShape.draw(canvas, paintShadow);
		roundRectShape.draw(canvas, paintDstOut);

		XulUtils.restoreCanvas(canvas);
		XulUtils.restoreCanvas(canvas);
	}

	canvas.setBitmap(null);
	return output;
}
 
Example 18
Source File: HolographicOutlineHelper.java    From LB-Launcher with Apache License 2.0 4 votes vote down vote up
void applyExpensiveOutlineWithBlur(Bitmap srcDst, Canvas srcDstCanvas, int color,
        int outlineColor, boolean clipAlpha) {

    // We start by removing most of the alpha channel so as to ignore shadows, and
    // other types of partial transparency when defining the shape of the object
    if (clipAlpha) {
        int[] srcBuffer = new int[srcDst.getWidth() * srcDst.getHeight()];
        srcDst.getPixels(srcBuffer,
                0, srcDst.getWidth(), 0, 0, srcDst.getWidth(), srcDst.getHeight());
        for (int i = 0; i < srcBuffer.length; i++) {
            final int alpha = srcBuffer[i] >>> 24;
            if (alpha < 188) {
                srcBuffer[i] = 0;
            }
        }
        srcDst.setPixels(srcBuffer,
                0, srcDst.getWidth(), 0, 0, srcDst.getWidth(), srcDst.getHeight());
    }
    Bitmap glowShape = srcDst.extractAlpha();

    // calculate the outer blur first
    mBlurPaint.setMaskFilter(mMediumOuterBlurMaskFilter);
    int[] outerBlurOffset = new int[2];
    Bitmap thickOuterBlur = glowShape.extractAlpha(mBlurPaint, outerBlurOffset);

    mBlurPaint.setMaskFilter(mThinOuterBlurMaskFilter);
    int[] brightOutlineOffset = new int[2];
    Bitmap brightOutline = glowShape.extractAlpha(mBlurPaint, brightOutlineOffset);

    // calculate the inner blur
    srcDstCanvas.setBitmap(glowShape);
    srcDstCanvas.drawColor(0xFF000000, PorterDuff.Mode.SRC_OUT);
    mBlurPaint.setMaskFilter(mMediumInnerBlurMaskFilter);
    int[] thickInnerBlurOffset = new int[2];
    Bitmap thickInnerBlur = glowShape.extractAlpha(mBlurPaint, thickInnerBlurOffset);

    // mask out the inner blur
    srcDstCanvas.setBitmap(thickInnerBlur);
    srcDstCanvas.drawBitmap(glowShape, -thickInnerBlurOffset[0],
            -thickInnerBlurOffset[1], mErasePaint);
    srcDstCanvas.drawRect(0, 0, -thickInnerBlurOffset[0], thickInnerBlur.getHeight(),
            mErasePaint);
    srcDstCanvas.drawRect(0, 0, thickInnerBlur.getWidth(), -thickInnerBlurOffset[1],
            mErasePaint);

    // draw the inner and outer blur
    srcDstCanvas.setBitmap(srcDst);
    srcDstCanvas.drawColor(0, PorterDuff.Mode.CLEAR);
    mDrawPaint.setColor(color);
    srcDstCanvas.drawBitmap(thickInnerBlur, thickInnerBlurOffset[0], thickInnerBlurOffset[1],
            mDrawPaint);
    srcDstCanvas.drawBitmap(thickOuterBlur, outerBlurOffset[0], outerBlurOffset[1],
            mDrawPaint);

    // draw the bright outline
    mDrawPaint.setColor(outlineColor);
    srcDstCanvas.drawBitmap(brightOutline, brightOutlineOffset[0], brightOutlineOffset[1],
            mDrawPaint);

    // cleanup
    srcDstCanvas.setBitmap(null);
    brightOutline.recycle();
    thickOuterBlur.recycle();
    thickInnerBlur.recycle();
    glowShape.recycle();
}
 
Example 19
Source File: ActivityManager.java    From AndroidComponentPlugin with Apache License 2.0 4 votes vote down vote up
/**
 * Add a new {@link AppTask} for the calling application.  This will create a new
 * recents entry that is added to the <b>end</b> of all existing recents.
 *
 * @param activity The activity that is adding the entry.   This is used to help determine
 * the context that the new recents entry will be in.
 * @param intent The Intent that describes the recents entry.  This is the same Intent that
 * you would have used to launch the activity for it.  In generally you will want to set
 * both {@link Intent#FLAG_ACTIVITY_NEW_DOCUMENT} and
 * {@link Intent#FLAG_ACTIVITY_RETAIN_IN_RECENTS}; the latter is required since this recents
 * entry will exist without an activity, so it doesn't make sense to not retain it when
 * its activity disappears.  The given Intent here also must have an explicit ComponentName
 * set on it.
 * @param description Optional additional description information.
 * @param thumbnail Thumbnail to use for the recents entry.  Should be the size given by
 * {@link #getAppTaskThumbnailSize()}.  If the bitmap is not that exact size, it will be
 * recreated in your process, probably in a way you don't like, before the recents entry
 * is added.
 *
 * @return Returns the task id of the newly added app task, or -1 if the add failed.  The
 * most likely cause of failure is that there is no more room for more tasks for your app.
 */
public int addAppTask(@NonNull Activity activity, @NonNull Intent intent,
        @Nullable TaskDescription description, @NonNull Bitmap thumbnail) {
    Point size;
    synchronized (this) {
        ensureAppTaskThumbnailSizeLocked();
        size = mAppTaskThumbnailSize;
    }
    final int tw = thumbnail.getWidth();
    final int th = thumbnail.getHeight();
    if (tw != size.x || th != size.y) {
        Bitmap bm = Bitmap.createBitmap(size.x, size.y, thumbnail.getConfig());

        // Use ScaleType.CENTER_CROP, except we leave the top edge at the top.
        float scale;
        float dx = 0, dy = 0;
        if (tw * size.x > size.y * th) {
            scale = (float) size.x / (float) th;
            dx = (size.y - tw * scale) * 0.5f;
        } else {
            scale = (float) size.y / (float) tw;
            dy = (size.x - th * scale) * 0.5f;
        }
        Matrix matrix = new Matrix();
        matrix.setScale(scale, scale);
        matrix.postTranslate((int) (dx + 0.5f), 0);

        Canvas canvas = new Canvas(bm);
        canvas.drawBitmap(thumbnail, matrix, null);
        canvas.setBitmap(null);

        thumbnail = bm;
    }
    if (description == null) {
        description = new TaskDescription();
    }
    try {
        return getService().addAppTask(activity.getActivityToken(),
                intent, description, thumbnail);
    } catch (RemoteException e) {
        throw e.rethrowFromSystemServer();
    }
}
 
Example 20
Source File: ActivityThread.java    From AndroidComponentPlugin with Apache License 2.0 4 votes vote down vote up
private Bitmap createThumbnailBitmap(ActivityClientRecord r) {
    Bitmap thumbnail = mAvailThumbnailBitmap;
    try {
        if (thumbnail == null) {
            int w = mThumbnailWidth;
            int h;
            if (w < 0) {
                Resources res = r.activity.getResources();
                mThumbnailHeight = h =
                    res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_height);

                mThumbnailWidth = w =
                    res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_width);
            } else {
                h = mThumbnailHeight;
            }

            // On platforms where we don't want thumbnails, set dims to (0,0)
            if ((w > 0) && (h > 0)) {
                thumbnail = Bitmap.createBitmap(w, h, THUMBNAIL_FORMAT);
                thumbnail.eraseColor(0);
            }
        }

        if (thumbnail != null) {
            Canvas cv = mThumbnailCanvas;
            if (cv == null) {
                mThumbnailCanvas = cv = new Canvas();
            }

            cv.setBitmap(thumbnail);
            if (!r.activity.onCreateThumbnail(thumbnail, cv)) {
                mAvailThumbnailBitmap = thumbnail;
                thumbnail = null;
            }
            cv.setBitmap(null);
        }

    } catch (Exception e) {
        if (!mInstrumentation.onException(r.activity, e)) {
            throw new RuntimeException(
                    "Unable to create thumbnail of "
                    + r.intent.getComponent().toShortString()
                    + ": " + e.toString(), e);
        }
        thumbnail = null;
    }

    return thumbnail;
}