Question

I'm stuck on a simple problem which is driving me nuts. In the standard Android MapView overlay images have a shadow drawn for them automatically when you call the drawAt method. I want to recreate the same shadow effect, but I'm not sure how to make the shadow version of the image (which is drawn separately from the main image) align properly with the main image.

private static class SampleView extends View {
    private Drawable mDrawable;
    private int mMarkerXOffset;
    private int mMarkerYOffset;

    public SampleView(Context context) {
        super(context);

        mDrawable = context.getResources().getDrawable(R.drawable.icon); 
        mDrawable.setBounds(0, 0, mDrawable.getIntrinsicWidth(), mDrawable.getIntrinsicHeight()); 

        mMarkerXOffset = (mDrawable.getIntrinsicWidth() / 2);
        mMarkerYOffset = mDrawable.getIntrinsicHeight();
    }

    private void DrawNormalImg(Canvas canvas, int nX, int nY)  {   
        canvas.save(Canvas.MATRIX_SAVE_FLAG);   
        canvas.translate(nX, nY);   
        mDrawable.draw(canvas);   
        canvas.restore();   
    }   

    private void DrawShadowImg(Canvas canvas, int nX, int nY)  { 
        canvas.save(Canvas.MATRIX_SAVE_FLAG);

        mDrawable.setColorFilter(0x7f000000, PorterDuff.Mode.SRC_IN);   

        canvas.translate(nX,nY);   
        canvas.skew(-0.9F, 0.0F);   
        canvas.scale(1.0F, 0.5F);   

        mDrawable.draw(canvas);   
        mDrawable.clearColorFilter();   

        canvas.restore();   
    }  

    @Override protected void onDraw(Canvas canvas) {
        int nX = 100;   
        int nY = 50;   

        canvas.drawColor(Color.WHITE);

        DrawShadowImg(canvas, nX, nY);   
        DrawNormalImg(canvas, nX, nY);
    }
Was it helpful?

Solution

Nice question! I think the solution will be skew the image as a parallelogram. Consider an image of a map pin that looks something like this:

..X..
.XXX.
..X..
..|..
..|..
..|..

Where . is transparency. You would want to skew the image like this for the shadow:

     ..X..
    .XXX.
   ..X..
  ..|..
 ..|..
..|..

Notice the top and bottom are the same width as in the original image.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top