Breaking News
Loading...
Sunday, 9 September 2012

Draw bitmap with shadow on canvas

16:36
More examples of drawing on canvas of custom View listed HERE.

Last exercise demonstrate how to "Draw text with shadow on canvas". It can be modify to display bitmap with canvas.

 @Override
protected void onDraw(Canvas canvas) {

float w, h, cx, cy;
w = getWidth();
h = getHeight();
cx = w/2;
cy = h/2;

canvas.drawColor(Color.GRAY);

Bitmap myBitmap = BitmapFactory.decodeResource(
getResources(),
R.drawable.ic_launcher);

Paint shadowPaint = new Paint();
shadowPaint.setAntiAlias(true);
shadowPaint.setColor(Color.WHITE);
shadowPaint.setTextSize(45.0f);
shadowPaint.setStrokeWidth(2.0f);
shadowPaint.setStyle(Paint.Style.STROKE);
shadowPaint.setShadowLayer(5.0f, 10.0f, 10.0f, Color.BLACK);

canvas.drawText("http://android-er.blogspot.com/", 50, 200, shadowPaint);
canvas.drawBitmap(myBitmap, cx, cy, shadowPaint);

};


Run on Nexus One, Android 2.3.6

Draw bitmap with shadow on canvas, run on Nexus One, Android 2.3.6

BUT, NO SHADOW displayed if run on HTC One X of Android 4.0.3!

For API Level 11, you have to call setLayerType (int layerType, Paint paint) to specifies the type of layer backing the View.

 @Override
protected void onDraw(Canvas canvas) {

float w, h, cx, cy;
w = getWidth();
h = getHeight();
cx = w/2;
cy = h/2;

canvas.drawColor(Color.GRAY);

Bitmap myBitmap = BitmapFactory.decodeResource(
getResources(),
R.drawable.ic_launcher);

Paint shadowPaint = new Paint();
shadowPaint.setAntiAlias(true);
shadowPaint.setColor(Color.WHITE);
shadowPaint.setTextSize(45.0f);
shadowPaint.setStrokeWidth(2.0f);
shadowPaint.setStyle(Paint.Style.STROKE);
shadowPaint.setShadowLayer(5.0f, 10.0f, 10.0f, Color.BLACK);

//for android:minSdkVersion="11"
setLayerType(LAYER_TYPE_SOFTWARE, shadowPaint);

canvas.drawText("http://android-er.blogspot.com/", 50, 200, shadowPaint);
canvas.drawBitmap(myBitmap, cx, cy, shadowPaint);

};

Run on HTC One X, Android 4.0.3

Draw bitmap with shadow on canvas, run on HTC One X, Android 4.0.3


download filesDownload the files.

0 comments:

Post a Comment

 
Toggle Footer