前言
最近公司给我安排个效果,就是当网络差或者断网的时候,边框有警告效果。正好用最近复习的自定义控件来练手。
效果图
代码实现
public class WarningView extends View {
private int mWarningColor;
private Paint mPaint;
private int mBorderWidth = 10;
public WarningView(Context context) {
this(context,null);
}
public WarningView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs,0);
}
public WarningView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
setLayerType(LAYER_TYPE_SOFTWARE, null);
TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.WarningView);
mWarningColor = array.getColor(R.styleable.WarningView_warningColor, mWarningColor);
mBorderWidth = (int) array.getDimension(R.styleable.WarningView_borderWidth, mBorderWidth);
array.recycle();
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setStrokeWidth(mBorderWidth);
mPaint.setColor(mWarningColor);
mPaint.setStyle(Paint.Style.STROKE);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec);
setMeasuredDimension(width,height);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
mPaint.setMaskFilter(new BlurMaskFilter(20, BlurMaskFilter.Blur.SOLID));
RectF rectF = new RectF(0, 0, getWidth(), getHeight());
canvas.drawRoundRect(rectF, 0, 0, mPaint);
}
}
attrs.xml 文件
```
<declare-styleable name="WarningView">
<attr name="warningColor" format="color" />
<attr name="borderWidth" format="dimension" />
</declare-styleable>
```
MainActivity 代码
```
ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(mWarning, "alpha", 1f, 0.5f,0f);
objectAnimator.setRepeatCount(ValueAnimator.INFINITE);
objectAnimator.setDuration(2400);
mWarning.setVisibility(View.VISIBLE);
objectAnimator.start();
```
|