问题:
当我在activity中使用我的自定义视图时,然后我更改自定义视图的translateY。然后,自定义视图绘制在状态栏上。
当我删除CustomView.java中的代码
canvas.clipRect(0, 0, getWidth(), getHeight(), Region.Op.REPLACE);
时,它会没问题
但在实际情况中,我需要clipRect函数来限制。那么,我该如何计算剪辑范围。
请帮我修理一下。
布局文件:
<RelativeLayout
android:id="@+id/action_bar"
android:layout_width="match_parent"
android:layout_height="40dp"
android:background="#00e0e0">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Test Title" />
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:text="up"
android:textSize="32dp" />
</RelativeLayout>
<cn.bangnijiao.testunitdemo.CustomView
android:id="@+id/counterView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/action_bar"
android:layout_centerHorizontal="true" />
代码:
public class YActivity extends Activity {
TextView up;
CustomView customView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_y);
up = (TextView) findViewById(R.id.text);
customView = (CustomView) findViewById(R.id.counterView);
up.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
customView.setTranslationY(customView.getTranslationY() - 20);
}
});
findViewById(R.id.action_bar).bringToFront();
}
}
CustomView代码:
public class CustomView extends View {
private Paint mPaint;
int size = 120;
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
drawSeparatorsAndBackground(canvas);
}
private void drawSeparatorsAndBackground(Canvas canvas) {
mPaint.setColor(Color.YELLOW);
canvas.drawRect(0, 0, getWidth(), getHeight(), mPaint);
canvas.clipRect(0, 0, getWidth(), getHeight(), Region.Op.REPLACE);
mPaint.setColor(Color.BLACK);
int verticalCount = (getWidth() / size);
float[] verticalLines = new float[verticalCount * 4];
for (int i = 0; i < verticalCount; i++) {
verticalLines[i * 4 + 0] = i * size;
verticalLines[i * 4 + 1] = 0;
verticalLines[i * 4 + 2] = i * size;
verticalLines[i * 4 + 3] = getHeight();
}
canvas.drawLines(verticalLines, mPaint);
int hourHorizontalCount = (getHeight() / size);
float[] hourHorizontalLines = new float[hourHorizontalCount * 4];
for (int i = 0; i < hourHorizontalCount; i++) {
hourHorizontalLines[i * 4 + 0] = 0;
hourHorizontalLines[i * 4 + 1] = i * size;
hourHorizontalLines[i * 4 + 2] = getWidth();
hourHorizontalLines[i * 4 + 3] = i * size;
}
canvas.drawLines(hourHorizontalLines, mPaint);
}
}
答案 0 :(得分:0)
尝试canvas.save()和canvas.restore()
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int saveCount = canvas.save();
drawSeparatorsAndBackground(canvas);
canvas.restoreToCount(saveCount);
}