我有以下问题: 我在android上创建了一个自定义视图。我想通过缩放动画(pivotX =“50%”和pivotY =“50%”)来制作视图脉冲。 如果视图位于屏幕中间,则缩放工作正常。如果视图位于屏幕的左侧,则看起来pivotX值将为“75%”。 如果视图位于屏幕的右侧,则看起来pivotX值将为“25%”。
以下是我的观点代码:
public class TestView extends View
{
private Paint _paint = new Paint();
private int _x, _y;
public TestView( Context context, int x, int y )
{
super( context );
_x = x;
_y = y;
_paint.setAntiAlias( true );
_paint.setColor( Color.BLUE );
_paint.setStyle( Style.FILL );
}
@Override
protected void onDraw( Canvas canvas )
{
super.onDraw( canvas );
canvas.drawCircle( _x, _y, 100 , _paint );
}
}
以下是动画pulse.xml文件的代码:
<scale xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="100"
android:fromXScale="1"
android:fromYScale="1"
android:pivotX="50%"
android:pivotY="50%"
android:repeatCount="3"
android:repeatMode="reverse"
android:toXScale="1.7"
android:toYScale="1.7" >
</scale>
片段类的代码:
ViewGroup mainLayout = (ViewGroup) getView().findViewById( R.id.my_layout );
float y = screenHeigth / 2;
float x1 = screenWidth*3/4; // right hand side of the screen
dest1 = new TestView( getActivity(), x1, y );
mainLayout.addView( dest1 );
float x2 = screenWidth / 2; // in the middle of the screen
dest2 = new TestView( getActivity(), x2, y );
mainLayout.addView( dest2 );
float x3 = screenWidth / 4; // left hand side of the screen
dest3 = new TestView( getActivity(), x3, y );
mainLayout.addView( dest3 );
ScaleAnimation pulse = (ScaleAnimation) AnimationUtils.loadAnimation( getActivity(), R.anim.pulse );
dest1.startAnimation( pulse );
dest2.startAnimation( pulse );
dest3.startAnimation( pulse );
我做错了什么?也许我必须在我的TestView类中做一些事情?
答案 0 :(得分:0)
现在我知道了:-)谢谢你pskink带我走正确的道路。 问题是,我的TestView填充了整个父视图。因此,我视图的中心是父视图的中心,而不是绘制圆的中心。
以下是解决方案:
public class TestView extends View
{
private Paint _paint = new Paint();
private int _xRelativeToView, _yRelativeToView, _w, _radius;
public TestView( Context context, int xOfView, int yOfView )
{
super( context );
_w = 100;
_radius = _w / 2;
// set the coordinates of the circle within this view
_xRelativeToView = _radius;
_yRelativeToView = _radius;
// set the position of the view on the screen:
LayoutParams mparam = new LayoutParams( _w, _w ); // the view is as big as the circle
mparam.addRule( RelativeLayout.ALIGN_PARENT_LEFT );
mparam.setMargins( xOfView - _radius, yOfView - _radius, 0, 0 );
setLayoutParams( mparam );
// initialize paint
_paint.setAntiAlias( true );
_paint.setColor( Color.BLUE );
_paint.setStyle( Style.FILL );
}
@Override
protected void onDraw( Canvas canvas )
{
super.onDraw( canvas );
canvas.drawCircle( _xRelativeToView, _yRelativeToView, _radius, _paint );
}
}