2016-01-06 23 views
6

Tôi đang cố tạo một ShapeDrawable theo lập trình nhưng mã sau đây không hiển thị bất kỳ thứ gì.Lập trình tạo ShapeDrawable

ImageView image = new ImageView (context); 
image.setLayoutParams (new LayoutParams (200, 200)); 
ShapeDrawable badge = new ShapeDrawable (new OvalShape()); 
badge.setBounds (0, 0, 200, 200); 
badge.getPaint().setColor(Color.RED); 
ImageView image = new ImageView (context); 
image.setImageDrawable (badge); 
addView (image); 

Tôi có thể làm cho nó hoạt động với xml.

<?xml version="1.0" encoding="utf-8"?> 
<shape 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:shape="oval"> 
    <size 
     android:width="200px" 
     android:height="200px" /> 
    <solid 
     android:color="#F00" /> 
</shape> 

ImageView image = new ImageView (context); 
image.setLayoutParams (new LayoutParams (200, 200)); 
image.setImageResource (R.drawable.badge); 
addView (image); 

Nhưng tôi muốn tạo nó theo chương trình. Các xml hoạt động hoàn hảo do đó vấn đề không thể được với ImageView, nó phải được trong việc tạo ra các ShapeDrawable.

+1

Bạn đã thử đặt giới hạn bố cục cho số lần xem của mình chưa? Vui lòng thêm thông tin về bố cục nơi bạn thêm số lần xem hình ảnh vào –

+0

Điểm này là gì? ImageView image = new ImageView (ngữ cảnh); lần thứ hai? –

Trả lời

6

Sử dụng setIntrinsicWidthsetIntrinsicHeight thay vì setBounds để thiết lập chiều rộng và chiều cao.

ImageView image = new ImageView (context); 
image.setLayoutParams (new LayoutParams (200, 200)); 
ShapeDrawable badge = new ShapeDrawable (new OvalShape()); 
badge.setIntrinsicWidth (200); 
badge.setIntrinsicHeight (200); 
badge.getPaint().setColor(Color.RED); 
image.setImageDrawable (badge); 
addView (image); 
0

Bạn có thể cần phải tạo Lớp mở rộng hình dạng có thể vẽ được để ghi đè onDraw và sau đó tạo một phiên bản lớp học của bạn.

Ví dụ: (Source - kiểm tra liên kết ví dụ đầy đủ)

private static class MyShapeDrawable extends ShapeDrawable { 
      private Paint mStrokePaint = new Paint(Paint.ANTI_ALIAS_FLAG); 

      public MyShapeDrawable(Shape s) { 
       super(s); 
       mStrokePaint.setStyle(Paint.Style.STROKE); 
      } 

      public Paint getStrokePaint() { 
       return mStrokePaint; 
      } 

      @Override protected void onDraw(Shape s, Canvas c, Paint p) { 
       s.draw(c, p); 
       s.draw(c, mStrokePaint); 
      } 
     } 
Các vấn đề liên quan