RoundRectDrawable.java revision bf43be6ab14db8489f924d1673951f0c49014605
1/* 2 * Copyright (C) 2014 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16package android.support.v7.widget; 17 18import android.graphics.Canvas; 19import android.graphics.ColorFilter; 20import android.graphics.Outline; 21import android.graphics.Paint; 22import android.graphics.PixelFormat; 23import android.graphics.Rect; 24import android.graphics.RectF; 25import android.graphics.drawable.Drawable; 26 27/** 28 * Very simple drawable that draws a rounded rectangle background with arbitrary corners and also 29 * reports proper outline for L. 30 * <p> 31 * Simpler and uses less resources compared to GradientDrawable or ShapeDrawable. 32 */ 33class RoundRectDrawable extends Drawable { 34 float mRadius; 35 final Paint mPaint; 36 final RectF mBounds; 37 38 public RoundRectDrawable(int backgroundColor, float radius) { 39 mRadius = radius; 40 mPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG); 41 mPaint.setColor(backgroundColor); 42 mBounds = new RectF(); 43 } 44 45 @Override 46 public void draw(Canvas canvas) { 47 canvas.drawRoundRect(mBounds, mRadius, mRadius, mPaint); 48 } 49 50 @Override 51 protected void onBoundsChange(Rect bounds) { 52 super.onBoundsChange(bounds); 53 mBounds.set(bounds.left, bounds.top, bounds.right, bounds.bottom); 54 } 55 56 @Override 57 public void getOutline(Outline outline) { 58 outline.setRoundRect(getBounds(), mRadius); 59 } 60 61 public void setRadius(float radius) { 62 if (radius == mRadius) { 63 return; 64 } 65 mRadius = radius; 66 invalidateSelf(); 67 } 68 69 @Override 70 public void setAlpha(int alpha) { 71 // not supported because older versions do not support 72 } 73 74 @Override 75 public void setColorFilter(ColorFilter cf) { 76 // not supported because older versions do not support 77 } 78 79 @Override 80 public int getOpacity() { 81 return PixelFormat.OPAQUE; 82 } 83 84 public float getRadius() { 85 return mRadius; 86 } 87} 88