我正在尝试创建自己的自定义控件,我想在其中绘制一个文本在其中旋转的视图。控件基本上是一个带文本的圆圈。 以下是我的自定义视图类:
package com.helios;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Path.Direction;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
public class MyGraphicsView extends View {
int height;
int width;
Animation anim;
Context context;
public MyGraphicsView(Context context, AttributeSet attrs) {
super(context);
this.context = context;
TypedArray ta = context.obtainStyledAttributes(attrs,
R.styleable.mygraphicview);
height = ta.getDimensionPixelSize(R.styleable.mygraphicview_cellHeight,
1);
width = ta
.getDimensionPixelSize(R.styleable.mygraphicview_cellWidth, 1);
}
public void startanim(Canvas c) {
anim = new RotateAnimation(0, 360, height/2, width/2);
anim.setRepeatMode(Animation.REVERSE);
anim.setRepeatCount(Animation.INFINITE);
anim.setInterpolator(new AccelerateInterpolator());
startAnimation(anim);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// TODO Auto-generated method stub
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension(resolveSize(width, widthMeasureSpec),
resolveSize(height, heightMeasureSpec));
}
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
if (anim == null) {
startanim(canvas);
}
Path circle = new Path();
circle.addCircle(200, 200, width, Direction.CW);
Paint canvaspaint = new Paint();
canvaspaint.setColor(Color.BLUE);
canvas.drawPath(circle, canvaspaint);
Paint textpaint = new Paint();
textpaint.setColor(Color.GREEN);
canvas.drawTextOnPath("I am rohan Joshi, this is my animation", circle,
0, 0, textpaint);
}
}
以下是我的main.xml文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:mycontrol="http://schemas.android.com/apk/res/com.helios"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="@string/hello" />
<com.helios.MyGraphicsView mycontrol:cellWidth="40dip"
android:layout_width="wrap_content" android:layout_height="wrap_content"
mycontrol:cellHeight="40dip"></com.helios.MyGraphicsView>
</LinearLayout>
自定义视图未显示在任何位置。我做错了什么?
答案 0 :(得分:1)
请确保在startanim(Canvas c)
方法中调用anim.setDuration(10000);
(当然,无论您想要什么价值)。您当前拥有的动画设置为持续时间为0,因此它在技术上正在工作,它只是在0秒内完成,所以它是即时的。
你也应该改变这个:
circle.addCircle(width/2, height/2, width / 2.5f, Direction.CW);
当您的画布宽度为40时,您正在创建一个从0开始的圆偏移200.所以,如果我是正确的,那么您将从画布上绘制它。这将在画布的中心绘制圆圈。