- 作者:Mr.Egg
- 状态:未完成
- 转载请注明,虽然写的不好但是最少让我知道下
简单的商品打折控件实现
首先,上效果图
那么问题来了,怎么实现
首先分析,这个肯定要自定义View实现。与这个最像的肯定是TextView。
继承于TextView(同样可用于ImageView,这里只是测试使用不然应该用ImageView,因为内容应该是图片)
接着是绘制界面(阴影是用来显示倒计时的,暂时没用到所以不做解释)
要实现斜着的长条,首先绘制一条横向矩形
然后沿着白色矩形左下角顶点逆时针旋转(设为335°)
显然左上角过小,向右平移最后绘上文字(记得计算距离长度,用于适配)
最后,附上代码:
package microcloud.org.cn.testhelloworld;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Build;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.TextView;
/**
* Created by Mr.Egg on 2016/11/19.
*/
public class FuckView extends TextView {
private int defaultRotate = 315;
private String labelText = "default";
private int labelColor = Color.WHITE;
private int textColor = Color.BLACK;
public FuckView(Context context) {
super(context);
}
public FuckView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public FuckView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public FuckView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int width = getMeasuredWidth();
int height = getMeasuredHeight();
//draw a translucent in top
Paint timPaint = new Paint();
timPaint.setColor(Color.parseColor("#30000000"));
timPaint.setStyle(Paint.Style.FILL);
canvas.drawRect(0f, 0f, width, height / 2f, timPaint);
//draw a left mark
Paint discountPaint = new Paint();
discountPaint.setColor(labelColor);
discountPaint.setStyle(Paint.Style.FILL);
canvas.rotate(defaultRotate, 0, height / 2 + height / 8);
canvas.translate(0, height / 8);
Rect rect = new Rect(0, height / 4, width, height / 2);
canvas.drawRect(rect, discountPaint);
//draw the left mark text
Paint textPaint = new Paint();
textPaint.setColor(textColor);
textPaint.setTextAlign(Paint.Align.LEFT);
textPaint.setTextSize(rect.height() / 2);
canvas.drawText(labelText, rect.left + height / 7, height / 2 - rect.bottom / 7, textPaint);
}
public FuckView retateView(int rotate) {
this.defaultRotate = rotate;
return this;
}
public FuckView setLabelText(String str) {
this.labelText = str;
return this;
}
public FuckView setLabelColor(int labelColor) {
this.labelColor = labelColor;
return this;
}
public FuckView setLabelTextColor(int textColor) {
this.textColor = textColor;
return this;
}
}