我有一个Canvas,它来自Picture类的beginRecording()方法。
我在画布上记录一些东西,然后调用endRecording()方法。
我想要记录的笔画在画布缩放后不会缩放。
我在Paint类中没有看到这样的功能。你可以设置setStrokeWidth(float w),但是:
- 如果w == 0,你会得到我想要的功能,但只有1px
- 如果w != 0,画布缩放意味着笔画也会缩放。
有什么想法吗?
我有一个Canvas,它来自Picture类的beginRecording()方法。
我在画布上记录一些东西,然后调用endRecording()方法。
我想要记录的笔画在画布缩放后不会缩放。
我在Paint类中没有看到这样的功能。你可以设置setStrokeWidth(float w),但是:
- 如果w == 0,你会得到我想要的功能,但只有1px
- 如果w != 0,画布缩放意味着笔画也会缩放。
有什么想法吗?
从当前变换矩阵中提取比例,并使用其逆来设置描边宽度。
你可能需要在自定义的SVG对象中跟踪你的宽度。当对象被缩放时,你可以找到新宽度与初始大小之间的比率,并将其乘以初始描边宽度。它不一定是宽度,也可以是高度或对角线长度。这取决于你的对象如何缩放。
或者你可以看看这个是否已经满足了你的需求:
由于解决方案包括扩展类,因此我将发布详细信息。 我没有进行广泛的测试,只是在我需要它的上下文中进行了测试。
我想从操作列表中获取Drawable,就像Picture.recording()的方式一样。
幸运的是,Path对象可以记录这些操作,然后我们可以将它们绘制到画布上。
不幸的是,通过canvas.drawPath()绘制它不提供无缩放笔画功能。
所以感谢@Andrew给出的提示,我已经扩展了Shape,类似于PathShape,但在onResize()中有一些不同的逻辑。
public class NonScalingStrokePathShape extends Shape{
private Path mPath;
private float mInitialWidth;
private float mInitialHeight;
private float mCurrentWidth;
private float mCurrentHeight;
public NonScalingStrokePathShape(Path pPath, float pInitialWidth, float pInitialHeight) {
mPath = pPath;
mInitialWidth = pInitialWidth;
mInitialHeight = pInitialHeight;
mCurrentWidth = mInitialWidth;
mCurrentHeight = mInitialHeight;
}
@Override
public void draw(Canvas canvas, Paint paint) {
canvas.drawPath(mPath,paint);
}
@Override
protected void onResize(float width, float height) {
Matrix matrix = new Matrix();
matrix.setScale(width / mCurrentWidth, height / mCurrentHeight);
mCurrentWidth = width;
mCurrentHeight = height;
mPath.transform(matrix);
}
@Override
public NonScalingStrokePathShape clone() throws CloneNotSupportedException {
NonScalingStrokePathShape shape = (NonScalingStrokePathShape) super.clone();
shape.mPath = new Path(mPath);
shape.mInitialHeight = mInitialHeight;
shape.mInitialWidth = mInitialWidth;
shape.mCurrentWidth = mInitialWidth;
shape.mCurrentHeight = mInitialHeight;
return shape;
}
}
这可以用于ShapeDrawable中,ShapeDrawable是一个Drawable,通过调用Shape的resize(float w, float h)方法已经考虑了边界大小调整。