Posts

Showing posts with the label Android Canvas

Android Canvas Clear With Transparency

Answer : Use the following. canvas.drawColor(Color.TRANSPARENT,Mode.CLEAR); The solution was to create a secondary canvas and bitmap to draw on. My Custom View's onSizeChanged() method looked like @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); bitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888); bitmap.eraseColor(Color.TRANSPARENT); temp = new Canvas(bitmap); } and the onDrawMethod looks like @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); temp.drawColor(Color.argb(80, 0, 0, 0)); temp.drawCircle(centerPosX, centerPosY, 200, transparentPaint); canvas.drawBitmap(bitmap, 0, 0, null); } where transparentPaint is declared in the onstructor as transparentPaint = new Paint(); transparentPaint.setColor(getResources().getColor(android.R.color.transparent)); transparentPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode....

Android Center Text On Canvas

Image
Answer : Try the following: Paint textPaint = new Paint(); textPaint.setTextAlign(Paint.Align.CENTER); int xPos = (canvas.getWidth() / 2); int yPos = (int) ((canvas.getHeight() / 2) - ((textPaint.descent() + textPaint.ascent()) / 2)) ; //((textPaint.descent() + textPaint.ascent()) / 2) is the distance from the baseline to the center. canvas.drawText("Hello", xPos, yPos, textPaint); Center with Paint.getTextBounds() : private Rect r = new Rect(); private void drawCenter(Canvas canvas, Paint paint, String text) { canvas.getClipBounds(r); int cHeight = r.height(); int cWidth = r.width(); paint.setTextAlign(Paint.Align.LEFT); paint.getTextBounds(text, 0, text.length(), r); float x = cWidth / 2f - r.width() / 2f - r.left; float y = cHeight / 2f + r.height() / 2f - r.bottom; canvas.drawText(text, x, y, paint); } Paint.Align.CENTER doesn't mean that the reference point of the text is vertically centered. The reference point ...