Android Paint setShadowLayer()忽略其Paint的颜色

时间:2011-08-29 12:50:28

标签: android android-canvas paint shadow

我正在尝试以编程方式创建一个Bitmap,并且发现绘制一个阴影的Rect忽略了传入的颜色arg。我简化了这种情况 - 代码只是绘制了一个旋转的蓝色方块,应该有一个灰色的阴影,但阴影总是蓝色的:

main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#fff"
    android:padding="40dp"
    >
</LinearLayout>

RotateRectShadowActivity.java:
public class RotateRectShadowActivity extends Activity {
    private LinearLayout mMainLayout;
    private ImageView mImageView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        LayoutInflater factory = LayoutInflater.from( this );
        mMainLayout = (LinearLayout) factory.inflate( R.layout.main, null );

        mImageView = new ImageView(this);

        Rect rect = new Rect(0, 0, 300, 300);

        Bitmap outerBm = Bitmap.createBitmap(
                rect.width(), rect.height(), Bitmap.Config.ARGB_8888);
        Bitmap innerBm = Bitmap.createBitmap(
                rect.width()-50, rect.height()-50, Bitmap.Config.ARGB_8888);

        Canvas outerCanvas = new Canvas(outerBm);
        Canvas innerCanvas = new Canvas(innerBm);
        outerCanvas.rotate(3);

        rect.left += 25;
        rect.top += 25;
        rect.right += 25;
        rect.bottom += 25;

        Paint shadowPaint = new Paint();
        shadowPaint.setShadowLayer(12, 12, 12, 0xFF555555);
        shadowPaint.setColor(0xFF555555);

        innerCanvas.drawRect(rect, shadowPaint);

        Paint rectPaint = new Paint();
        rectPaint.setColor(Color.BLUE);
        innerCanvas.drawRect(rect, rectPaint);
        outerCanvas.drawBitmap(innerBm, 0, 0, shadowPaint);

        mImageView.setImageBitmap(outerBm);
        mMainLayout.addView(mImageView);
        setContentView(mMainLayout);
    }
}

RotateRectShadow

我不明白为什么调用outerCanvas.drawBitmap(innerBm,0,0,shadowPaint);需要一个Paint,因为我试图通过innerCanvas在innerBm上绘制阴影,但是当我传递null时,根本就没有阴影。

1 个答案:

答案 0 :(得分:4)

您的内部位图太小了,它会切割矩形的边缘。试试这个:

    Bitmap outerBm = Bitmap.createBitmap( 
            rect.width(), rect.height(), Bitmap.Config.ARGB_8888); 
    Bitmap innerBm = Bitmap.createBitmap( 
            rect.width() + 50, rect.height() + 50, Bitmap.Config.ARGB_8888); 

    Canvas outerCanvas = new Canvas(outerBm); 
    Canvas innerCanvas = new Canvas(innerBm); 
    outerCanvas.rotate(3); 

    rect.left += 25; 
    rect.top += 25; 
    rect.right -= 25; 
    rect.bottom -= 25; 

    Paint shadowPaint = new Paint();
    shadowPaint.setColor(Color.BLUE);; 
    shadowPaint.setShadowLayer(12, 12, 12, 0xFF555555); 

    innerCanvas.drawRect(rect, shadowPaint); 

    outerCanvas.drawBitmap(innerBm, 0, 0, null);