如何使用自定义视图,例如设置drawable

时间:2011-11-10 17:00:47

标签: android

我认为我对如何使用自定义视图感到有些困惑。我跟随着来自Square的Eric Burke的演讲中的幻灯片(来自今年的anddevcon,幻灯片在这里:http://www.andevcon.com/AndevCon_II/downloadpresentation.aspx?aid=Taming_Android__User_Experience_Lessons_from_Square_pdf.zip&sid=2)。

他的代码,或者至少他在幻灯片中展示的部分,是这样的:

public class EditablePhoto extends View {

    private Bitmap framedPhoto;
    private Bitmap image;
    private Drawable placeholder;

    public EditablePhoto(Context context) {
        super(context);
    }

    @Override protected void onMeasure(int widthMeasureSpec,
                                       int heightMeasureSpec) {
        int measuredWidth = getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec);
        int measuredHeight = getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec);

        //ensure view always square
        int min = Math.min(measuredHeight, measuredWidth);
        setMeasuredDimension(min, min);

    }

    @Override
    protected void onDraw(Canvas canvas) {
        if(placeholder == null && image==null) return;

        if(framedPhoto == null) {
            createFramedPhoto(Math.min(getWidth(), getHeight()));
        }

        canvas.drawBitmap(framedPhoto, 0, 0, null);
    }

    private void createFramedPhoto(int size) {

        Drawable imageDrawable = (image!=null)
                ? new BitmapDrawable(image) : placeholder;

        Bitmap output = Bitmap.createBitmap(size, size, 
                Bitmap.Config.ARGB_8888);

        Canvas canvas = new Canvas(output);

        RectF outerRect = new RectF(0, 0, size, size);
        float outerRadius = size / 18f;

        //Red rectangle

        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setColor(Color.RED);

        canvas.drawRoundRect(outerRect, outerRadius, outerRadius, paint);

        paint.setXfermode(new PorterDuffXfermode(
                PorterDuff.Mode.SRC_IN));

         imageDrawable.setBounds(0, 0, size, size);
        canvas.saveLayer(outerRect, paint, Canvas.ALL_SAVE_FLAG);
        imageDrawable.draw(canvas);
        canvas.restore();
    }
}

我没有得到的是如何实际使用此视图....在何时何地设置位图,这是本课程中的私有字段...?

一般困惑,并会喜欢一些启蒙。

2 个答案:

答案 0 :(得分:0)

超过一年过去了,但我希望这能帮助那些寻找正确答案的人。就我而言,我推出了这行代码

framedPhoto = output;

作为createFramedPhoto()方法中的最后一个。有用。 在该示例中,作者创建了一个圆角矩形作为背景,然后他使用XOR模式在其上绘制位图,因此圆角矩形外的所有像素都将被修剪掉。

答案 1 :(得分:-1)

OnDraw()是在画布上绘制视图的方法。在这里你也可以分析onDraw()将fisrt调用CreateFramePhoto,然后在画布上绘制这个Bitmap。

您可以在布局中添加此customView,无论是从xml还是在Java Class

1)通过Xml:

<EditablePhoto  android:layout_height="wrap_content"
         android:layout_gravity="center_vertical"
                ..........................
/>

不要forgate为这种情况添加构造函数EditablePhoto(Context context,AttributeSet attributeSet)

2)通过Java类:

EditablePhoto editablePhoto = new EditablePhoto(this);
addView(editablePhoto) // or do anthing you want with this