android view增加点击效果,如:iReader书架书籍点击变暗

    Android开发中,View的图片是动态生成的,我们需要增加点击效果。像iReader 的书架中的书籍,点击变暗。


使用很简单:

    ImageView iv = (ImageView) this.findViewById(R.id.image_view1);

    Drawable d = Drawable.createFromPath("picPath");

        StateListDrawable sld = createSLD(this, d);
        iv.setImageDrawable(sld);


///增加如下两个方法:

public Drawable createDrawable(Drawable d, Paint p) {

        BitmapDrawable bd = (BitmapDrawable) d;
        Bitmap b = bd.getBitmap();
        Bitmap bitmap = Bitmap.createBitmap(bd.getIntrinsicWidth(),
                bd.getIntrinsicHeight(), Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        canvas.drawBitmap(b, 0, 0, p); // 关键代码,使用新的Paint画原图,

        return new BitmapDrawable(bitmap);
    }


    /** 设置Selector。 本次只增加点击变暗的效果,注释的代码为更多的效果*/ 
    public StateListDrawable createSLD(Context context, Drawable drawable) {
        StateListDrawable bg = new StateListDrawable();
        Paint p = new Paint();
        p.setColor(0x40222222); //Paint ARGB色值,A = 0x40 不透明。RGB222222 暗色


        Drawable normal = drawable;
        Drawable pressed = createDrawable(drawable, p);
        // p = new Paint();
        // p.setColor(0x8000FF00);
        // Drawable focused = createDrawable(drawable, p);
        // p = new Paint();
        // p.setColor(0x800000FF);
        // Drawable unable = createDrawable(drawable, p);
        // View.PRESSED_ENABLED_STATE_SET
        bg.addState(new int[] { android.R.attr.state_pressed,
                android.R.attr.state_enabled }, pressed);
        // View.ENABLED_FOCUSED_STATE_SET
        // bg.addState(new int[] { android.R.attr.state_enabled,
        // android.R.attr.state_focused }, focused);
        // View.ENABLED_STATE_SET
        bg.addState(new int[] { android.R.attr.state_enabled }, normal);
        // View.FOCUSED_STATE_SET
        // bg.addState(new int[] { android.R.attr.state_focused }, focused);
        // // View.WINDOW_FOCUSED_STATE_SET
        // bg.addState(new int[] { android.R.attr.state_window_focused },
        // unable);
        // View.EMPTY_STATE_SET
        bg.addState(new int[] {}, normal);
        return bg;
    }

你可能感兴趣的:(android)