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
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
 Download the files.
Download the files.

 
2 comments:
very useful, thanks
It is very nice.But how to get shadow for bitmap with black color like textview.
Post a Comment